0

I use forEach almost every time that I'm facing a node list or an actual array, but there are times, in which I can't do so, like when I want to create 5 div elements, I'm bound to do this with for loop

for (let i = 0; i < 4; i++) {
   //my code to do some repetitive code ...

   const myDiv = document.createElement('div');
   myDiv.classList.add(`${myDiv}${i}`)
   document.appendChild(myDiv);
}

The question is how can I do the same work with forEach, when there is no actual array or node list that can be used forEach method.

since forEach does the work asynchronously unlike for loop, I think it would be more beneficial move, am I wrong, any idea?

Andres2142
  • 2,622
  • 2
  • 14
  • 19
AbeIsWatching
  • 159
  • 1
  • 11

2 Answers2

1
Array(3).fill().forEach((e,i) => {
  const myDiv = document.createElement('div');
  myDiv.classList.add(`${myDiv}${i}`)
  document.appendChild(myDiv);
})
Ismail Rubad
  • 1,458
  • 2
  • 13
  • 27
  • To which OP responded (above) by asking, what if I want 100 iterations? – Jeremy Thille Apr 06 '20 at 14:48
  • 1
    @AbeIsWatching look at the `forEach` equivalent, it's providing no real benefit, actually creating a useless array in the memory and reducing the code readability. compare it to ur clean old school `for` loop – Mechanic Apr 06 '20 at 14:58
  • yeah, e represent each member of the array and i the index of that member in that array.Thanks, that is the right answer but almost every one says, stick to for loop for these cases. – AbeIsWatching Apr 06 '20 at 14:58
  • @Ismail You should add the disclaimer to your answer since though it technically answers the question, you think a for loop is better. Especially considering the OP's original assumption that a `forEach` was asynchronous – Ruan Mendes Apr 06 '20 at 18:05
0

There is no problem in using the for loop, and that is exactly the right place to use a for loop (or a while).

Mechanic
  • 5,015
  • 4
  • 15
  • 38