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 0if(CHECKIFarray[k]ISEMPTYSLOT)continue;// DO THE OTHER STAFF}
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.
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.
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.
Hi Hasnain, under the hood
forEach()
using something like the below code.Using
forEach()
can skip some unnecessary heavy calculation. What if we accidentally setarray[400] = "SOME VALUE"
and the other slots are empty, then we have to unnecessarily execute our heavy calculation function400
times that will affect the performance.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.
No one says that
forEach()
is faster thanfor...loop
. For the same piece of codefor..loop
will be always faster thenforEach()
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.Hmm. Thanks for writing the post.
Thanks for giving me the feedback.