By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

JavaScript forEach Tutorial

Tutorial on how to best loop through arrays in javascript.

Edited: 2012-12-30 04:22

Those familiar with foreach from other languages, may be wondering if there is a JavaScript equivalent that you can use. There is the forEach function, but this may not work in very old browser versions.

Note. for each is different than forEach, where the former is deprecated.

Using the forEach loop function

The JavasCript forEach function is not supported by older browsers, however most newer browsers does have it implemented – and it doesn't suffer from the same problems as the first method we mentioned.

var a = ["a", "b", "c"];
a.forEach(function(entry) {

If you prefer less messy code, you can also declare a function before using forEach.

var aNArr = new Array();
aNArr[0] = '0';
aNArr[3] = '3';
aNArr[4] = '4';
aNArr[5] = '5';
aNArr[7] = '7';

function alertElements(element, index, array) {

How to make it work in older browsers

We would recommend that you either use the old way of iterating over an array, or stick to purely using forEach.

See also: Ditch support for Old Browsers

You could also use the For loop instead of using the forEach function loop. An example of how to do that is included below:

var aNArr = ["one", "two", "three"];
aNArr[3] = 'four';
for (var counter = 0; counter < aNArr.length; counter++) {

We used the alert method to demonstrate how to work with the array elements. The counter variable will be automatically incremented each time the process has finished, until aNArr.length has been reached.

See also

  1. Get the Count of Elements in an Array
  2. While and For loops