Using a forEach loop with JavaScript

U

I honestly feel like I’ve been living in the stone age. For years I’ve always used a standard for loop when iterating JavaScript arrays accessing the property with the index of my for loop. No longer, it’s time to upgrade (my brain) and use the forEach loop.

The traditional for loop of an array

The number of times I’ve written a JavaScript for loop on an array as follows is uncountable.

[code]
var myArray = [“a”,”b”,”c”];

for (var i = 0; i < myArray.length; i++) {
var value = myArray[i];

console.log(value);
}
[/code]

I’ve always hated this approach as my standard server-side languages I use, such as PHP and C#, have a foreach binding function built-in. Time to come out of the stone age…

JavaScript forEach loop of an array

Let’s upgrade my brain and use some newer JavaScript techniques to forEach an array. It’s of course quite simple and matches the format I am used to with my server-side languages.

[code]
var myArray = [“a”,”b”,”c”];

myArray.forEach(function(value) {
console.log(value);
});
[/code]

The forEach executes a callback function for each element in the array; exactly what I expect and now I don’t need to manually target the element by its position in the array.

In the above example I am using an anonymous JavaScript function, to help organize my code I can provide an actual JavaScript function that is called instead as follows:

[code]
var myArray = [“a”,”b”,”c”];

myArray.forEach(myCallbackFunction);

function myCallbackFunction(value) {
console.log(value);
}
[/code]

This is a nice subtle change to avoid nesting my code with anonymous functions.

About the author

By Jamie

My Books