AbeIsWatching
AbeIsWatching

Reputation: 159

replacing for loop with forEach method

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?

Upvotes: 0

Views: 90

Answers (2)

Mechanic
Mechanic

Reputation: 5380

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

Upvotes: 0

Ismail Rubad
Ismail Rubad

Reputation: 1468

Array(3).fill().forEach((e,i) => {
  const myDiv = document.createElement('div');
  myDiv.classList.add(`${myDiv}${i}`)
  document.appendChild(myDiv);
})

Upvotes: 1

Related Questions