Videos
IF you have array than make use of forEach
array.forEach(ele=> {
});
that way you can keep code clean and easy to understand and dont have to do length related code.
Break is not going to work with forEach but you can write return for coming out of forEach like
array.forEach(ele=> {
ele.array.forEach(ele=> {
//do stuff
return;
});
});
Note:
- for loop is faster.
- forEach is slower, but better fits functional programming paradigms.
Answer is based on title of question : Best Practice that why given suggestion to make use of forEach over for.
Concerning saving array.length: Even though in the early days of JavaScript it made a difference to save the .length value in a variable, modern JavaScript engines will run the for loop just as fast if you write it as in the first version.
Iterating backward is also not guaranteed to run faster on modern engines. There is also the consideration that CPUs are optimised to anticipate forward memory references, although this will only be relevant when the JS engine has decided to store the array as a contiguous block of memory.
As for the use of labels: most would not consider this best practice. Where the previous optimisation (concerning .length) concerns all iterations of the loop, this issue only applies to a single exit out of both loops. Whatever solution you use, it represents constant time, and could not be a determining factor in the overall performance of the loop.
So certainly in this case, I would go with good coding habits over tiny optimisation considerations. When you want to exit just the current loop, a single break is enough.
If you want to exit quickly from nested loops, then consider placing them in a function, so you can use return:
function performNestedLoop(array, array2) {
for(let i = 0; i < array.length; i++){
for(var j = 0; j < array2.length; j++){
//dostuff
if (exitCondition) return;
}
}
}
As to best practice: this really depends on what you need to achieve. There are several array methods that provide iteration, like forEach, map, reduce, reduceRight, filter, some, every, find, findIndex, includes,... each with their purpose. If they fit the purpose, then go with them. If you don't need the index, but just the value, then use for..of. If you really need every speck of optimatisation, then the old fashioned for loop is a likely winner.