Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

292
Visualizações
knowing when to use a loop or map

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(() => (
      ?
      
      ));

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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
about 4 years ago · Juan Pablo Isaza Relatório

0

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((number, index) => 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 contrived and not very good, but I hope you get the point. Let me know in the comments if you have any query

Update For your case you could use map as below

links.map(link => {
  let border = link.boundary.points;
  drawPath(canvas, ctx, border, '#AA1111', '#AA1111', 0.2);
});

about 4 years ago · Juan Pablo Isaza Relatório

0

First and foremost if you know you need to break out early then you need to use a loop as you can not return early with forEach and map (without the use of something like filter).

Also specific for react you will get a re-render if state or properties change. Using map will create a new array (at least the reference to the array) which will get you a re-render which is often desired.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda