Home > Software engineering >  knowing when to use a loop or map
knowing when to use a loop or map

Time:02-28

Trying to learn by coding (React), my question: React uses map() everywhere, so can we replace every loop for example for loop with map ? When is good to use map and when for loop ? in following example i have used for loop, should i be using map ?

how would this be changed to map ?:

 const links = currentLinks;
      for (let i = 0; i < links.length;   i) {
        let border = links[i].boundary.points;
        drawPath(canvas, ctx, border, '#AA1111', '#AA1111', 0.2);
      }
      
      
      
      -----------------
      
      links.map(() => (
      ?
      
      ));

CodePudding user response:

It's a matter of preference, but in my book, using loops a lot means someone is less experienced. The main difference is that you need to keep the state when you're using a loop. And when you're using a state, you need to think of a name for it and - believe it or not - that's sometimes the hardest part. On the other hand, .map(), .filter(), .reduce() etc. are just expressions.

Use whatever you prefer, but use it wisely.

That being said, sometimes using a loop makes more sense. The rule of thumb is that whenever your code generates some kind of side effect, using a loop is more logical. Consider these two examples:

for (const fruit of fruits) {
    draw(fruit);
}

// or:

fruits.forEach(
    fruit => draw(fruit) // makes sense
);

// vs.

fruits.map(
    fruit => draw(fruit)
);

All will work and do the same thing, but the last one is rather amateurish to do. It returns an array of whatever draw() returns and that return value is never used, so the purpose of using an expression is lost.

To sum up:

  • expression? use .map()
  • side effect? use loops

CodePudding user response:

map => For Transformation or Projection - It gives a new collection

loops => For doing some operation (on the collection itself or in general) - It does not return anything

For example

const data = [1, 2, 3, 4, 5]

You want to get the doubles of each number in the array

const doubled = data.map((index, number) => number * 2);

//-- Output 

[2, 4, 6, 8, 10]

You want to call some method (or perform some action) if the item is between 2 and 5

data.forEach(number => { 
    if(number > 2 && number < 5){
        //call some method
    }
    else{
        //..... do some other work
    }
}

or

for(let i=0; i< data.length; i  ){
    const number = data[i];
    if(number > 2 && number < 5){
        //call some method
    }
    else{
        //..... do some other work
    }
}

I know the examples are shitty, not very good, but I hope you get the point. Let me know in the comments if you have any query

  • Related