Javascript forEach Example
Very often we run in cases when we just have a collection of elements and a necessity to loop through it.
EcmaScript5 suggests a simple forEach()
method for such purpose.
So, if you’re tired of writing countless for (var i = 0; i < arr.length; ++i)
loops, let’s look how it works.
For example, we have an array of numbers and we want to output factorials of its elements
function fact(n) { if (n == 1 || n == 0) return 1; return n * fact(n - 1); } [ 0, 1, 2, 3 ].forEach(function(elem) { document.writeln(fact(elem)); // outputs 1 1 2 6 });
In case you need to perform some actions with array object here’s one more way with a little bit different syntax. Let’s say we want to check if an array contains a increasing by one sequense of numbers
function outputElement(elem, ind, array) { if (ind == 0) document.writeln('arr[' + ind + '] = ' + elem + "; Sequence started
"); else if (array[ind - 1] == elem - 1) document.writeln('arr[' + ind + '] = ' + elem + "; Larger by 1 than previous
"); else document.writeln('arr[' + ind + '] = ' + elem + "; Sequence failed
"); } [ 0, 1, 2, 4, 5, 6 ].forEach(outputElement);
Also note that undefined elements of an array don’t count while iterating
var counter = 0; [ 0, , 1, , 2, , 3].forEach(function(element) { ++counter; }); document.writeln(counter); // outputs 4 not 7
This approach works fine with a collection of DOM elements. Let’s suppose we have following structure
- 0
- 1
- 2
- 3
- 4
So, we can select li
elements and iterate over them using following JS code
function fact(n) { if (n == 1 || n == 0) return 1; return n * fact(n - 1); } var obj = document.getElementsByTagName("li"); Array.prototype.forEach.call(obj, function(elem) { document.writeln(fact(elem.innerText)); });
Using forEach one can also iterate over object properties
var o = { first: '0', second: '1', third: '2', fourth: '3' }; Object.getOwnPropertyNames(o).forEach(function(element) { document.writeln(element + " = " + o[element]); });
Sometimes you might want to break forEach
loop. In this case good practice way is to use every()
wich breaks looping when returns false
[ 0, 1, 2, 3, 4 ].every(function(element, index, array) { document.writeln(element); return element < 3; });
Or, probably, you want to do something with the elements of an array until you find a special element and you will use some()
[ 0, 1, 2, 3, 4 ].some(function(element, index, array) { document.writeln(element); return element == 3; });
Note, that every()
breaks the loop when returning false, otherwise some()
does it when returning true
You can download the full source code of this example here: JavascriptForEach