Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the .length property gets evaluated on every iteration of a for loop? [duplicate]

Tags:

javascript

I've been unable to find the answer to this, say for example you have the array:

var myArray = ["a","b","c","d","e","f","g"]; // pretend I define up to 1000 elements

One simple approach to iterate through the array would be:

for(var i=0; i<myArray.length; i++){
    console.log(myArray[i]);
}

What I'm trying to figure out is if the .length property will be evaluated on each iteration, then if I use:

my len = myArray.length;
for(var i=0; i<len i++){
    console.log(myArray[i]);
}

Does the 2nd approach will be a performance improvement ? Does the JS engine will calculate the length on each iteration?

like image 615
isJustMe Avatar asked Oct 22 '25 17:10

isJustMe


1 Answers

It does! I like this solution

for(var i=0, len=myArray.length; i<len; i++){
    console.log(myArray[i]);
}

It's just a little cleaner than the one you pasted.

like image 124
Mulan Avatar answered Oct 24 '25 08:10

Mulan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!