I'm doing a tutorial on JavaScript. The following is from a section on performance:
Each statement in a loop, including the for statement, is executed for each iteration of the loop. Statements or assignments that can be placed outside the loop will make the loop run faster.
This is given as an example of bad code:
var i;
for (i = 0; i < arr.length; i++) {
And this is given as an example of good code:
var i;
var l = arr.length;
for (i = 0; i < l; i++) {
This is not something I can remember seeing as a best practice in languages that are more focused on performance than JavaScript. In fact, the bad code example seems to be preferred.
Is this best practice something particular for JavaScript, or is is true for other languages?
2 Answers 2
Bad Practice
for (i = 0; i < arr.length; i++) {
For every iteration in the loop, the condition is evaluated. If it is being arr.length then every time you are trying to access length property from arr. However, on the other hand, if you are storing it in a variable you are avoiding that operation.
4 Comments
Of all the ways to loop in javascript, the for-in loop is the safest in my opinion.
It can loop through the properties in an object.
let user = {first:"billy", last:"bob"};
for(let i in user){
console.log(i);
console.log(user[i]);
}
It doesn't throw an error if the variable is null
let empty = null;
for (let i in empty){
}
It works with arrays
let arr = [3,2,1];
for (let i in arr){
console.log(i);
console.log(arr[i]);
}
.map .filter .reduce .forEach throw errors with anything but arrays(null, objects etc)
So if you want one loop that works for everything, for-in is you what you want.
for (var i=0, n=arr.length; i<n; i++) {- If the iteration changes the length of the array, then you need to NOT cache the lengthlengthof an array every iteration (unless you're expecting it to change), it would be better to put the length of the array into a variable, and then check that variable. That said, you should consider a better tutorial site than W3schools, which is notoriously unreliable