The accepted answer is not right because any decent engine should be able to hoist the property load out of the loop with so simple loop bodies.

See this jsperf - at least in V8 it is interesting to see how actually storing it in a variable changes the register allocation - in the code where variable is used the sum variable is stored on the stack whereas with the array.length-in-a-loop-code it is stored in a register. I assume something similar is happening in SpiderMonkey and Opera too.

According to the author, JSPerf is used incorrectly, 70% of the time. These broken jsperfs as given in all answers here give misleading results and people draw wrong conclusions from them.

Some red flags are putting code in the test cases instead of functions, not testing the result for correctness or using some mechanism of eliminating dead code elimination, defining function in setup or test cases instead of global.. For consistency you will want to warm-up the test functions before any benchmark too, so that compiling doesn't happen in the timed section.

Answer from Esailija on Stack Overflow
🌐
Reddit
reddit.com › r/node › how does the array.length property is calculated in a loop?
r/node on Reddit: How does the array.length property is calculated in a loop?
September 1, 2022 -

Consider the following piece of code:

let array = [1, 2, 3, 4, 5, 6, 7];
for (let i = 0; i < array.length; i++) {
  console.log[array[i]];
}

Here, it the array's length calculated by the runtime for each iteration? Or is it stored somewhere the first time it is calculated and called from the storage for the subsequent iterations?

But, if the block inside the loop involves modifying the number of array elements, then it would actually have to calculate, right?

And where can I find information about this in the TC39 specs or MDN?

🌐
Stack Overflow
stackoverflow.com › questions › 72839030 › for-loop-while-referring-to-an-array-with-length
javascript - For Loop while referring to an array with Length - Stack Overflow
I'm very new to javascript and have just recently learned about For loops. I have a variable that consists of an array containing a bunch names, and I would like to add last names to each of them. I
Discussions

javascript - For-loop performance: storing array length in a variable - Stack Overflow
Consider two versions of the same loop iteration: for (var i = 0; i More on stackoverflow.com
🌐 stackoverflow.com
For ... loop with array.length issue
Huh? The output? Array only 5? However: changed it into ’ for (var i = 0; i < 9; i++) and then the array was completed: // Array(9) [ 9, 8, 7, 6, 5, 4, 3, 2, 1 ] · So: With ‘i < arr.length’ my loop goes only 5 x, output Array(5) [ 9, 8, 7, 6, 5 ] However ‘arr.length = 9’, as checked ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
5
0
July 21, 2020
JavaScript for loop - using variable set to array.length rather than using array.length directly
Hi everyone, I've just completed the 'Drop It' challenge (this one) but my for loop only worked correctly when I assigned a variable to arr.length and used that as the conditional, rather than using i More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
August 15, 2016
javascript - Do loops check the array.length every time when comparing i against array.length? - Stack Overflow
So unless I'm mistaken, the complexity ... for loop scope. However, I suspect that in this case the reason the example's programmer chose this approach is simply just a habit they picked up in another language and carried forwards JavaScript. ... Save this answer. ... Show activity on this post. One reason to do this would be to iterate only over the initial length of an array while new ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Mimo
mimo.org › glossary › javascript › array-length
JavaScript Array Length: Master Data Handling
The .length property is fundamental to array manipulation. Here are its most common applications in a structured format. | Use Case | Example | Explanation | | --- | --- | --- | | Iteration | for (let i = 0; i < arr.length; i++) | The most common way to create a for loop that runs exactly once for each element.
🌐
Programiz
programiz.com › javascript › library › array › length
JavaScript Array length
var languages = ["JavaScript", "Python", "C++", "Java", "Lua"]; // languages.length can be used to find out // the number of times to loop over an array · for (i = 0; i < languages.length; i++){ console.log(languages[i]); } Output · JavaScript Python C++ Java Lua ·
🌐
freeCodeCamp
freecodecamp.org › news › javascript-array-length-tutorial
JavaScript Array Length – How to Find the Length of an Array in JS
September 4, 2024 - You can use this to check if an array is empty and, if not, iterate through the elements in it. Javascript has a <.length> property that returns the size of an array as a number(integer).
🌐
Career Karma
careerkarma.com › blog › javascript › javascript array length: a complete guide
JavaScript Array Length: A Complete Guide | Career Karma
December 1, 2023 - Then, we create a JavaScript for loop that iterates through each item in the dancer_ages list and adds it to the sum variable. Notice that we use the dancer_ages.length property to tell our program how many times it should execute.
Top answer
1 of 6
42

The accepted answer is not right because any decent engine should be able to hoist the property load out of the loop with so simple loop bodies.

See this jsperf - at least in V8 it is interesting to see how actually storing it in a variable changes the register allocation - in the code where variable is used the sum variable is stored on the stack whereas with the array.length-in-a-loop-code it is stored in a register. I assume something similar is happening in SpiderMonkey and Opera too.

According to the author, JSPerf is used incorrectly, 70% of the time. These broken jsperfs as given in all answers here give misleading results and people draw wrong conclusions from them.

Some red flags are putting code in the test cases instead of functions, not testing the result for correctness or using some mechanism of eliminating dead code elimination, defining function in setup or test cases instead of global.. For consistency you will want to warm-up the test functions before any benchmark too, so that compiling doesn't happen in the timed section.

2 of 6
37

Update: 16/12/2015

As this answer still seems to get a lot of views I wanted to re-examine the problem as browsers and JS engines continue to evolve.

Rather than using JSPerf I've put together some code to loop through arrays using both methods mentioned in the original question. I've put the code into functions to break down the functionality as would hopefully be done in a real world application:

function getTestArray(numEntries) {
  var testArray = [];
  for (var i = 0; i < numEntries; i++) {
    testArray.push(Math.random());
  }
  return testArray;
}

function testInVariable(testArray) {
  for (var i = 0; i < testArray.length; i++) {
    doSomethingAwesome(testArray[i]);
  }
}

function testInLoop(testArray) {
  var len = testArray.length;
  for (var i = 0; i < len; i++) {
    doSomethingAwesome(testArray[i]);
  }
}

function doSomethingAwesome(i) {
  return i + 2;
}

function runAndAverageTest(testToRun, testArray, numTimesToRun) {
  var totalTime = 0;
  for (var i = 0; i < numTimesToRun; i++) {
    var start = new Date();
    testToRun(testArray);
    var end = new Date();
    totalTime += (end - start);
  }
  return totalTime / numTimesToRun;
}

function runTests() {
  var smallTestArray = getTestArray(10000);
  var largeTestArray = getTestArray(10000000);

  var smallTestInLoop = runAndAverageTest(testInLoop, smallTestArray, 5);
  var largeTestInLoop = runAndAverageTest(testInLoop, largeTestArray, 5);
  var smallTestVariable = runAndAverageTest(testInVariable, smallTestArray, 5);
  var largeTestVariable = runAndAverageTest(testInVariable, largeTestArray, 5);

  console.log("Length in for statement (small array): " + smallTestInLoop + "ms");
  console.log("Length in for statement (large array): " + largeTestInLoop + "ms");
  console.log("Length in variable (small array): " + smallTestVariable + "ms");
  console.log("Length in variable (large array): " + largeTestVariable + "ms");
}

console.log("Iteration 1");
runTests();
console.log("Iteration 2");
runTests();
console.log("Iteration 3");
runTests();

In order to achieve as fair a test as possible each test is run 5 times and the results averaged. I've also run the entire test including generation of the array 3 times. Testing on Chrome on my machine indicated that the time it took using each method was almost identical.

It's important to remember that this example is a bit of a toy example, in fact most examples taken out of the context of your application are likely to yield unreliable information because the other things your code is doing may be affecting the performance directly or indirectly.

The bottom line

The best way to determine what performs best for your application is to test it yourself! JS engines, browser technology and CPU technology are constantly evolving so it's imperative that you always test performance for yourself within the context of your application. It's also worth asking yourself whether you have a performance problem at all, if you don't then time spent making micro optimizations that are imperceptible to the user could be better spent fixing bugs and adding features, leading to happier users :).

Original Answer:

The latter one would be slightly faster. The length property does not iterate over the array to check the number of elements, but every time it is called on the array, that array must be dereferenced. By storing the length in a variable the array dereference is not necessary each iteration of the loop.

If you're interested in the performance of different ways of looping through an array in javascript then take a look at this jsperf

Find elsewhere
🌐
LinkedIn
linkedin.com › pulse › efficient-way-use-arraylength-loops-gopesh-tiwari
Efficient way to use array.length in loops
March 5, 2021 - for (var i = 0; i < array.length; i++) { console.log(array[i]); ... This is fine when we are working with smaller arrays, but if we are processing very large array then this code will recalculate array size in every iteration of this loop and ...
🌐
freeCodeCamp
forum.freecodecamp.org › curriculum help
For ... loop with array.length issue - Curriculum Help - The freeCodeCamp Forum
July 21, 2020 - I was toying with for … loops, bumped into something weird function turnaround (arr) { var nwarr = []; // console.log(arr.length); for (var i = 0; i
🌐
freeCodeCamp
forum.freecodecamp.org › t › javascript-for-loop-using-variable-set-to-array-length-rather-than-using-array-length-directly › 28312
JavaScript for loop - using variable set to array.length rather than using array.length directly
August 15, 2016 - Hi everyone, I've just completed the 'Drop It' challenge (this one) but my for loop only worked correctly when I assigned a variable to arr.length and used that as the conditional, rather than using i
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-find-the-length-of-an-array-in-javascript
How to Find the Length of an Array in JavaScript ? - GeeksforGeeks
July 23, 2025 - Example: Finding the length of the array using the for loop by itertating through the each element of the array.
🌐
Shiksha
shiksha.com › home › it & software › it & software articles › programming articles › how to find the javascript array length
How to Find the JavaScript Array Length - Shiksha Online
December 18, 2023 - Length -1 mainly means the -1 portion. We got this when running a for loop over an array: for I = 0; I array. ... The number of items in an array can be set or returned using JavaScript's array length property.
Top answer
1 of 6
30

A loop consisting of three parts is executed as follows:

for (A; B; C)

A - Executed before the enumeration
B - condition to test
C - expression after each enumeration (so, not if B evaluated to false)

So, yes: The .length property of an array is checked at each enumeration if it's constructed as for(var i=0; i<array.length; i++). For micro-optimisation, it's efficient to store the length of an array in a temporary variable (see also: What's the fastest way to loop through an array in JavaScript?).

Equivalent to for (var i=0; i<array.length; i++) { ... }:

var i = 0;
while (i < array.length) {
    ...
    i++;
}
2 of 6
13
Is it worth it? (obviously yes, why else he will do it this way?)

Absolutely yes. Because, as you say, loop will calculate array length each time. So this will cause an enormous overhead. Run the following code snippets in your firebug or chrome dev tool vs.

// create an array with 50.000 items
(function(){
    window.items = [];
    for (var i = 0; i < 50000; i++) {
        items.push(i);
    }
})();

// a profiler function that will return given function's execution time in milliseconds
var getExecutionTime = function(fn) {
    var start = new Date().getTime();
    fn();
    var end = new Date().getTime();
    console.log(end - start);
}

var optimized = function() {
    var newItems = [];
    for (var i = 0, len = items.length; i < len; i++) {
        newItems.push(items[i]);
    }
};


var unOptimized = function() {
    var newItems= [];
    for (var i = 0; i < items.length; i++) {
        newItems.push(items[i]);
    }
};

getExecutionTime(optimized);
getExecutionTime(unOptimized);

Here is the approximate results in various browsers

Browser    optimized    unOptimized
Firefox    14           26
Chrome     15           32
IE9        22           40
IE8        82           157
IE7        76           148 

So consider it again, and use optimized way :)
Note: I tried to work this code on jsPerf but I couldn't access jsPerf now. I guess, it is down when I tried.

🌐
DEV Community
dev.to › kalashin1 › comment › 192c1
You use array.length in a for loop when you want to iterate over the array an... - DEV Community
Say we want to print the values inside an array one after the other we could do it like this. const myArray = [1,2,3,4,5] //then using for for(var i = 0; i < myArray.length; i++) { console.log(i) //prints out 1, 2, 3, 4, 5 } The thing is that with for loops you need to pass a starter counter, that is a variable that specifies where to begin the loop from, that is why we set i = 0.
🌐
MSR
rajamsr.com › home › javascript array length: how to use it effectively
JavaScript Array Length: How to Use It Effectively | MSR - Web Dev Simplified
January 31, 2024 - If you don’t want to use an array length property to check the length, you can use forEach() or a for loop to iterate through the array elements to find the length of an array.
🌐
O'Reilly
oreilly.com › library › view › javascript-the-definitive › 9781449393854 › ch07s06.html
Iterating Arrays - JavaScript: The Definitive Guide, 6th Edition [Book]
May 3, 2011 - Content preview from JavaScript: ... for object o var values = [] // Store matching property values in this array for(var i = 0; i < keys.length; i++) { // For each index in the array var key = keys[i]; // Get the key at that ...
Author: David Flanagan
Published: 2011
Pages: 1093
🌐
Python Examples
pythonexamples.org › javascript › Array › length
JavaScript Array length - Syntax & Examples
We use a for loop to iterate through each element of the array using the length property. Inside the loop, we log each element to the console. const fruits = ['apple', 'banana', 'cherry']; for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]); } ... In this JavaScript tutorial, we ...
🌐
Scaler
scaler.com › home › topics › javascript array length
Javascript Array Length Property - Scaler Topics
February 27, 2024 - Explanation: In the above code, we have assumed an array of elements 11,12,13,14,15 then we have assumed a variable named len which stores the array length in javascript using numbers.length property after that we have run a loop from 0 to len in which the loop in every iteration is decreasing the value of element by 1.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › length
Array: length - JavaScript - MDN Web Docs
The length data property of an Array instance represents the number of slots in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array. It may be greater than the number of elements if the array is sparse.