
Javascript Array Helper: forEach
Looping or iterating through an array is a very common task you often need to do in javascript. ES6 javascript provides a handy array helper function for this…. the forEach.
First, let’s look at how we would do this in older ES5 javascript.
var colors = ['red', 'blue', 'green']; for (var i = 0; i < colors.length; i++) { console.log(colors[i]); }
Javascript forEach Helper
Now iterating through an array can be simplified by using the forEach. Here is how the example above would be re-written.
var colors = ['red', 'blue', 'green']; colors.forEach(function(color) { console.log(color); });
The way this works is that for each array element a callback function will get called where you can do something within that function.
A Practical Example
Suppose we have an array of numbers and we want to sum up all the numbers and get a total. Here is how you could do it using forEach.
var numbers = [10, 15, 7, 8]; var sum=0; numbers.forEach(function(number) { sum+=number; }); console.log(sum);
Hope this helps, in my next post I will discuss if the array .map function.