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. 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

Modern Array Iteration Methods

JavaScript language revisions and updates have added the following iteration methods for arrays: forEach, map, and filter. These methods accept a function as their first argument.[1] 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. The callback function modifies 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 forEach callback function skips undefined elements of sparse arrays.[2]

The map Method

The map method creates a new array whose values are determined by the return value of a callback function passed to map as it iterates over the elements of the original array it is invoked on. This example multiplies each original array value 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 explicitly return anything for values that are not strings, undefined was returned for those values. The array returned by the map method matches the length of the array it is invoked on. This occurs even for sparse arrays.[3]

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, returning a subset of the original based on the criteria specified in the callback function passed to it. 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-numbered 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. An optional second argument accepts an object which becomes the value of this inside the first argument function. ^
  2. 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, or when the delete operator is used to remove elements. ^
  3. The callback function doesn't process undefined elements in a sparse array but leaves them intact in the same order as the original array. ^