DEV Community

Discussion on: Why is using javascript “for loop” for array iteration a bad idea?

Collapse
_prosen profile image
Prosen Ghosh Author

Hi Hasnain, under the hood forEach() using something like the below code.

while(k < len){ // HERE len IS THE ACTUAL ARRAY LENGTH AND k START FROM 0
if(CHECK IF array[k] IS EMPTY SLOT)continue;
// DO THE OTHER STAFF
}
Enter fullscreen mode Exit fullscreen mode

Using forEach()can skip some unnecessary heavy calculation. What if we accidentally set array[400] = "SOME VALUE" and the other slots are empty, then we have to unnecessarily execute our heavy calculation function 400 times that will affect the performance.

Collapse
hasnaindev profile image
Muhammad Hasnain • Edited on

That is why we almost never use index in terms of manual assignment and use push method or array spreading instead. This is why it is also recommended to never use these constructor methods, unless of course, it is an absolute requirement which is almost quite rare.

This also does not improve performance either. Both use for loops and there is no evidence that forEach is faster than the for loop.

Thread Thread
_prosen profile image
Prosen Ghosh Author • Edited on

No one says that forEach() is faster than for...loop. For the same piece of code for..loop will be always faster then forEach() method unless we make any mistake in our code.

The above example code snippets for for..loop are written in such a way that, we can understand what can happen if we make this kind of mistake in our code.

Thread Thread
hasnaindev profile image
Muhammad Hasnain

Hmm. Thanks for writing the post.

Thread Thread
_prosen profile image
Prosen Ghosh Author

Thanks for giving me the feedback.