A few weeks ago, I heard that declaring the true/false condition variable outside of the loop was faster. So, I wanted to try it out.
So, basically, I made this code to see which is faster.
These are the two loops.
// Initialization
const arr = [1, 2, 3, 4, 5];
// Bad Loop
console.time("bad");
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
console.timeEnd("bad");
// Good Loop
console.time("good");
let l = arr.length;
for (let i = 0; i < l; i++) {
console.log(arr[i]);
}
console.timeEnd("good");
When the code is run, there is a significant difference in the time it takes to run the bad loop, versus the time it takes in the good loop. (No matter how quick the bad loop is, the good loop is always quicker.)
So, my question is why is this happening? The only difference between the two loops is the fact that the good loop defines the array length before the loop begins, while the bad loop gets it in the loop.