Javascript Array Iteration

There are several ways to iterate over arrays in JavaScript: some traditional and some new, as we will discuss and demonstrate on this page.

When we traverse an array, we access each of its elements in turn and perform some action. This is traditionally done using a for loop. This example modifies the array by multiplying each of its values times 2:

var ar = [1, 2, 3, 4, 5];
for (var i=0, len=ar.length; i<len; i++) {
    ar[i] *= 2; // multiply value times 2
}
console.log( ar ); // [2, 4, 6, 8, 10]

You may need to check each array element before you act on it to see whether it is undefined or null, or whether it is the correct type, etc. In the following example, we check to be sure the value is numeric:

var ar = ['zero', 1, 'two', 3, 'four', 5, null, 'six'];
var sum = 0; // to hold sum of numeric array values
for (var i=0, len=ar.length; i<len; i++) {
    // check to be sure current array value is numeric
    if ( typeof ar[i] === 'number' ) {
        sum += ar[i]; // if so, add its value to sum
    }
}
console.log( sum ); // 9

The above examples demonstrate the optimized form of the for loop, using a second variable (len) to hold the length of the array rather than checking it every iteration, as the traditional form does:

// traditional for loop checks length of ar each iteration
for (var i = 0; i < ar.length; i++) {
    // code here
}

JavaScript also includes a for-in loop which can be used to traverse array elements. However it iterates over inherited properties in addition to numerically indexed elements and is less efficient than a for loop. So its use for iterating over arrays is not recommended.

ECMAScript 5 Array Iteration Methods

The vast majority of browsers in current use support the new array iteration methods provided by ECMAScript 5: forEach, map, and filter[1]. These methods accept a function as their first argument.[2] Each element of the array is passed in turn to this function which accepts three arguments: the current element's value, its index, and the array itself. The function you define doesn't have to use all three arguments. In some cases you may only need to use the value of the array element, as we will show in our examples demonstrating these methods.

The forEach Method

The forEach method iterates over the elements of an array much like a regular for loop. However, you can't use the break statement to exit early as you can with a for loop. The forEach method does not return a value.

In the following example we declare an array and invoke forEach on it. We pass value, index, and array (v, i, a) to our function argument to modify the array, multiplying each value by 2 as we did in the for loop above:

var ar = [1, 2, 3, 4, 5];
ar.forEach( function(v, i, ar) { ar[i] = v*2; } );
console.log( ar ); // [2, 4, 6, 8, 10]

In the next example we create a new array rather than modifying the array forEach is invoked on. We only need to pass the value (v) to accomplish this:

var ar = [1, 2, 3, 4, 5];
var ar2 = []; // new array
// pass value, multiply times 2, and push to new array
ar.forEach( function(v) { ar2.push(v*2); } );
// view new array
console.log( ar2 ); // [2, 4, 6, 8, 10]

The array element value could be used in forEach for any number of purposes, from displaying in a list on a web page to inserting into a database. But if you want to create a new array based on values in the existing array, perhaps the map method is more suitable.

The map Method

The map method creates a new array. As each element of the existing array is passed to map's function argument in turn, the function's return value determines the value of the corresponding element of the new array. For this example we return the value (v) times 2:

var ar = [1, 2, 3, 4, 5];
var ar2 = ar.map( function(v) { return v*2; } );
console.log( ar2 ); // [2, 4, 6, 8, 10]

Here is another example use of the array map method to convert the first letter of each element's value to uppercase:

var ar = ['jan', 'feb', 'mar', 'apr', 'may'];
var ar2 = ar.map( function(v) {
    return v.charAt(0).toUpperCase() + v.slice(1);
} );
console.log( ar2 ); // [ "Jan", "Feb", "Mar", "Apr", "May" ]

As mentioned above when describing the for loop, you will often need to check the array element value's type before attempting to act on it. For this example, if your array includes values that are not strings, a JavaScript TypeError will be triggered. So we include a type check:

var ar = [1, 'jan', 'feb', 'mar', 'apr', 'may', false];
var ar2 = ar.map( function(v) {
    if ( typeof v === 'string' ) {
        return v.charAt(0).toUpperCase() + v.slice(1);
    }
} );
console.log( ar2 ); // [undefined, "Jan", "Feb", "Mar", "Apr", "May", undefined]

Notice that even though our function didn't return anything for values that are not strings, undefined was returned for those values. This is because the array returned by the map method matches the length of the array it is invoked on. This occurs even for sparse arrays.[3]

So we will revise our function to return the original value when the type is not string:

var ar = [1, 'jan', 'feb', 'mar', 'apr', 'may', false];
var ar2 = ar.map( function(v) {
    if ( typeof v === 'string' ) {
        return v.charAt(0).toUpperCase() + v.slice(1);
    } else {
        return v;
    }
} );
console.log( ar2 ); // [ 1, "Jan", "Feb", "Mar", "Apr", "May", false ]

What if we want our array to consist of only a particular type? We can use the filter method to achieve this.

The filter Method

The filter method returns a new array. It selects from the original array and returns a subset of it based on your criteria. We can use the filter method as follows to return an array containing only string values:

var ar = [1, 'jan', 'feb', 'mar', 'apr', 'may', false];
var ar2 = ar.filter( function(v) {
    if ( typeof v === 'string' ) {
        return true;
    }
} );
console.log( ar2 ); // [ "jan", "feb", "mar", "apr", "may" ]

The filter method inspects each element of the array in turn, and its function argument should return true or false to indicate whether the current element should be included in the returned array or not.

This example uses the modulo operator (%) to return an array containing only the even number values from the original array:

var ar = [1, 2, 3, 4, 5, 6];
var ar2 = ar.filter( function(v) { return v % 2 === 0; } );
console.log( ar2 ); // [2, 4, 6]

The filter method skips missing elements in sparse arrays. So it can be used to create a dense array from a sparse one:

var ar = [1, , , 4]; // sparse array
// using filter to return dense version of sparse array
var ar2 = ar.filter( function() { return true; } );
console.log( ar2 ); // [1, 4] 

Back to top


  1. Internet Explorer 8 does not support these methods. ^
  2. An optional second argument accepts an object which becomes the value of this inside the first argument function. ^
  3. A sparse array has some missing elements. This can occur when an array is defined with empty elements (such as when using the array constructor with a single numeric argument for example), or when the delete operator is used to remove elements. ^