What is the best practice for writing a JavaScript for loop?
I started out writing it like this:
for(var i = 0; i < array.length; i++){
//do stuff
}
But then I found that calculating the length on each pass is not ideal, so it should be more like:
var len = array.length;
for(var i = 0; i < len; i++){
//do stuff
}
But then the loop is faster if you decrease rather than increase:
var lenArr = array.length - 1;
for(var len = lenArr; len > 0; len--){
//do stuff
}
This kind of loop however doesn't really work if you want to break just one loop in a cluster of nested loops, so you should therefore get into the habit of using labels:
var lenArr = array.length - 1;
var lenArr2 = array2.length - 1;
loop1: for(var len = lenArr; len > 0; len--){
loop2: for(var len2 = lenArr2; len2 > 0; len2--){
//do stuff
break loop2;
}
}
Is there something else that will need to change, or is this the best practice for writing for loops in JavaScript?
forloops entirely whenever possible - unlike array methods, they require manual iteration, do not have any abstraction, have hoisting issues when newbie developers are usingvar, and are not composable. The Array methods are better in every respect except speed, and speed is rarely something to worry about unless you're writing a library. But this is opinion-based.break loop2;... that looks like awful code