[image] johnsciutto: console.log(i, arr.length); Yes! Adding i to the console made it clear to me. Many thanks! Answer from roelvanschaik on forum.freecodecamp.org
🌐
W3Schools
w3schools.com › jsref › jsref_length_array.asp
JavaScript Array length Property
Array[ ] Array( ) at() concat() constructor copyWithin() entries() every() fill() filter() find() findIndex() findLast() findLastIndex() flat() flatMap() forEach() from() includes() indexOf() isArray() join() keys() lastIndexOf() length map() of() pop() prototype push() reduce() reduceRight() rest (...) reverse() shift() slice() some() sort() splice() spread (...) toReversed() toSorted() toSpliced() toString() unshift() values() valueOf() with() JS Boolean
🌐
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.
Top answer
1 of 16
5290

Three main options:

  1. for (var i = 0; i < xs.length; i++) { console.log(xs[i]); }
  2. xs.forEach((x, i) => console.log(x));
  3. for (const x of xs) { console.log(x); }

Detailed examples are below.


1. Sequential for loop:

var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
    console.log(myStringArray[i]);
    //Do something
}

Pros

  • Works on every environment
  • You can use break and continue flow control statements

Cons

  • Too verbose
  • Imperative
  • Easy to have off-by-one errors (sometimes also called a fence post error)

2. Array.prototype.forEach:

The ES5 specification introduced a lot of beneficial array methods. One of them, the Array.prototype.forEach, gave us a concise way to iterate over an array:

const array = ["one", "two", "three"]
array.forEach(function (item, index) {
  console.log(item, index);
});

Being almost ten years as the time of writing that the ES5 specification was released (Dec. 2009), it has been implemented by nearly all modern engines in the desktop, server, and mobile environments, so it's safe to use them.

And with the ES6 arrow function syntax, it's even more succinct:

array.forEach(item => console.log(item));

Arrow functions are also widely implemented unless you plan to support ancient platforms (e.g., Internet Explorer 11); you are also safe to go.

Pros

  • Very short and succinct.
  • Declarative

Cons

  • Cannot use break / continue

Normally, you can replace the need to break out of imperative loops by filtering the array elements before iterating them, for example:

array.filter(item => item.condition < 10)
     .forEach(item => console.log(item))

Keep in mind if you are iterating an array to build another array from it, you should use map. I've seen this anti-pattern so many times.

Anti-pattern:

const numbers = [1,2,3,4,5], doubled = [];

numbers.forEach((n, i) => { doubled[i] = n * 2 });

Proper use case of map:

const numbers = [1,2,3,4,5];
const doubled = numbers.map(n => n * 2);

console.log(doubled);

Also, if you are trying to reduce the array to a value, for example, you want to sum an array of numbers, you should use the reduce method.

Anti-pattern:

const numbers = [1,2,3,4,5];
const sum = 0;
numbers.forEach(num => { sum += num });

Proper use of reduce:

const numbers = [1,2,3,4,5];
const sum = numbers.reduce((total, n) => total + n, 0);

console.log(sum);

3. ES6 for-of statement:

The ES6 standard introduces the concept of iterable objects and defines a new construct for traversing data, the for...of statement.

This statement works for any kind of iterable object and also for generators (any object that has a \[Symbol.iterator\] property).

Array objects are by definition built-in iterables in ES6, so you can use this statement on them:

let colors = ['red', 'green', 'blue'];
for (const color of colors){
    console.log(color);
}

Pros

  • It can iterate over a large variety of objects.
  • Can use normal flow control statements (break / continue).
  • Useful to iterate serially asynchronous values.

Cons

  • If you are targeting older browsers, the transpiled output might surprise you.

Do not use for...in

@zipcodeman suggests the use of the for...in statement, but for iterating arrays for-in should be avoided, that statement is meant to enumerate object properties.

It shouldn't be used for array-like objects because:

  • The order of iteration is not guaranteed; the array indexes may not be visited in numeric order.
  • Inherited properties are also enumerated.

The second point is that it can give you a lot of problems, for example, if you extend the Array.prototype object to include a method there, that property will also be enumerated.

For example:

Array.prototype.foo = "foo!";
var array = ['a', 'b', 'c'];

for (var i in array) {
    console.log(array[i]);
}

The above code will console log "a", "b", "c", and "foo!".

That can be particularly a problem if you use some library that relies heavily on native prototypes augmentation (such as MooTools).

The for-in statement, as I said before, is there to enumerate object properties, for example:

var obj = {
    "a": 1,
    "b": 2,
    "c": 3
};

for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        // or if (Object.prototype.hasOwnProperty.call(obj,prop)) for safety...
        console.log("prop: " + prop + " value: " + obj[prop])
    }
}

In the above example, the hasOwnProperty method allows you to enumerate only own properties. That's it, only the properties that the object physically has, no inherited properties.

I would recommend you to read the following article:

  • Enumeration VS Iteration
2 of 16
1210

Yes, assuming your implementation includes the for...of feature introduced in ECMAScript 2015 (the "Harmony" release)... which is a pretty safe assumption these days.

It works like this:

// REQUIRES ECMASCRIPT 2015+
var s, myStringArray = ["Hello", "World"];
for (s of myStringArray) {
  // ... do something with s ...
}

Or better yet, since ECMAScript 2015 also provides block-scoped variables:

// REQUIRES ECMASCRIPT 2015+
const myStringArray = ["Hello", "World"];
for (const s of myStringArray) {
  // ... do something with s ...
}
// s is no longer defined here

(The variable s is different on each iteration, but can still be declared const inside the loop body as long as it isn't modified there.)

A note on sparse arrays: an array in JavaScript may not actually store as many items as reported by its length; that number is simply one greater than the highest index at which a value is stored. If the array holds fewer elements than indicated by its length, its said to be sparse. For example, it's perfectly legitimate to have an array with items only at indexes 3, 12, and 247; the length of such an array is 248, though it is only actually storing 3 values. If you try to access an item at any other index, the array will appear to have the undefined value there, but the array is nonetheless is distinct from one that actually has undefined values stored. You can see this difference in a number of ways, for example in the way the Node REPL displays arrays:

> a              // array with only one item, at index 12
[ <12 empty items>, 1 ]
> a[0]           // appears to have undefined at index 0
undefined
> a[0]=undefined // but if we put an actual undefined there
undefined
> a              // it now looks like this
[ undefined, <11 empty items>, 1 ]

So when you want to "loop through" an array, you have a question to answer: do you want to loop over the full range indicated by its length and process undefineds for any missing elements, or do you only want to process the elements actually present? There are plenty of applications for both approaches; it just depends on what you're using the array for.

If you iterate over an array with for..of, the body of the loop is executed length times, and the loop control variable is set to undefined for any items not actually present in the array. Depending on the details of your "do something with" code, that behavior may be what you want, but if not, you should use a different approach.

Of course, some developers have no choice but to use a different approach anyway, because for whatever reason they're targeting a version of JavaScript that doesn't yet support for...of.

As long as your JavaScript implementation is compliant with the previous edition of the ECMAScript specification (which rules out, for example, versions of Internet Explorer before 9), then you can use the Array#forEach iterator method instead of a loop. In that case, you pass a function to be called on each item in the array:

var myStringArray = [ "Hello", "World" ];
myStringArray.forEach( function(s) { 
     // ... do something with s ...
} );

You can of course use an arrow function if your implementation supports ES6+:

myStringArray.forEach( s => { 
     // ... do something with s ...
} );

Unlike for...of, .forEach only calls the function for elements that are actually present in the array. If passed our hypothetical array with three elements and a length of 248, it will only call the function three times, not 248 times. If this is how you want to handle sparse arrays, .forEach may be the way to go even if your interpreter supports for...of.

The final option, which works in all versions of JavaScript, is an explicit counting loop. You simply count from 0 up to one less than the length and use the counter as an index. The basic loop looks like this:

var i, s, myStringArray = [ "Hello", "World" ], len = myStringArray.length;
for (i=0; i<len; ++i) {
  s = myStringArray[i];
  // ... do something with s ...
}

One advantage of this approach is that you can choose how to handle sparse arrays. The above code will run the body of the loop the full length times, with s set to undefined for any missing elements, just like for..of; if you instead want to handle only the actually-present elements of a sparse array, like .forEach, you can add a simple in test on the index:

var i, s, myStringArray = [ "Hello", "World" ], len = myStringArray.length;
for (i=0; i<len; ++i) {
  if (i in myStringArray) {
    s = myStringArray[i];
    // ... do something with s ...
  }
}

Depending on your implementation's optimizations, assigning the length value to the local variable (as opposed to including the full myStringArray.length expression in the loop condition) can make a significant difference in performance since it skips a property lookup each time through. You may see the length caching done in the loop initialization clause, like this:

var i, len, myStringArray = [ "Hello", "World" ];
for (len = myStringArray.length, i=0; i<len; ++i) {

The explicit counting loop also means you have access to the index of each value, should you want it. The index is also passed as an extra parameter to the function you pass to forEach, so you can access it that way as well:

myStringArray.forEach( (s,i) => {
   // ... do something with s and i ...
});

for...of doesn't give you the index associated with each object, but as long as the object you're iterating over is actually an instance of Array (and not one of the other iterable types for..of works on), you can use the Array#entries method to change it to an array of [index, item] pairs, and then iterate over that:

for (const [i, s] of myStringArray.entries()) {
  // ... do something with s and i ...
}

The for...in syntax mentioned by others is for looping over an object's properties; since an Array in JavaScript is just an object with numeric property names (and an automatically-updated length property), you can theoretically loop over an Array with it. But the problem is that it doesn't restrict itself to the numeric property values (remember that even methods are actually just properties whose value is a closure), nor is it guaranteed to iterate over those in numeric order. Therefore, the for...in syntax should not be used for looping through Arrays.

🌐
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?

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

🌐
Codecademy
codecademy.com › forum_questions › 529bc86980ff33fe45011652
Array and Loops 13/14 | Codecademy
For a for loop to iterate through the array and stop at the end, you need to use the array’s length property, array.length. This will let JavaScript know how many pockets the array has, because i will guide JavaScript through the searching process.
Find elsewhere
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › length
Array: length - JavaScript | MDN
The length data property of an Array instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.
🌐
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 ·
🌐
Team Treehouse
teamtreehouse.com › community › why-do-you-need-i-arraylength-condition-for-javascript-for-loops
why do you need i< array.length condition for javascript for loops
August 12, 2016 - The "i<array.length" you mention is the second part, the condition. As long as this statement is true, the code inside the code block of the loop will run. ... This is the initial statement of the for loop. It runs before the loop begins.
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.

🌐
O'Reilly
oreilly.com › library › view › javascript-the-definitive › 9781449393854 › ch07s06.html
Iterating Arrays - JavaScript: The Definitive Guide, 6th Edition [Book]
May 3, 2011 - for(var i = 0, len = keys.length; i < len; i++) { // loop body remains the same } These examples assume that the array is dense and that all elements contain valid data. If this is not the case, you should test the array elements before using them.
Author   David Flanagan
Published   2011
Pages   1093
🌐
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.
🌐
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
June 20, 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 < arr.length dire…
🌐
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
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).
🌐
Codecademy
codecademy.com › forum_questions › 5286bae4548c35db2400242d
Why store the length of the array in a variable instead of using .length? | Codecademy
In this case, run the function and get us the value to which we may compare our control. ... The .length method is called 1000 times. var arr = new Array(1000); for (var i=0, n=arr.length; i<n; i++) { // code }
🌐
CoreUI
coreui.io › answers › how-to-get-the-length-of-an-array-in-javascript
How to get the length of an array in JavaScript · CoreUI
September 19, 2025 - The length property returns the number of elements in the array as an integer. In this example, fruits.length returns 3 because there are three elements in the array. This property is automatically updated whenever elements are added or removed ...
🌐
W3Schools
w3schools.com › js › js_loop_for.asp
JavaScript for Loop
JS Arrays JS Array Methods JS Array Search JS Array Sort JS Array Iterations JS Array Reference JS Array Const JS Sets · JS Sets JS Set Methods JS Set Logic JS Set WeakSet JS Set Reference JS Maps · JS Maps JS Map Methods JS Map WeakMap JS Map Reference JS Iterations · JS Loops JS Iterables JS Iterators JS Generators JS Math