Helping you solve those tough coding problems!

Using a forEach loop with JavaScript Using a forEach loop with JavaScript

Published on Apr 7, 2019 by Jamie Munro

I honestly feel like I've been living in the stone age. For years I've always used a standard for loop when iterating a JavaScript array 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.


var myArray = ["a","b","c"];

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


I've always hated this approach as my standard server-side languages I use, such as PHP and C#, have a foreach 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.


var myArray = ["a","b","c"];

myArray.forEach(function(value) {
	console.log(value);
});


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:


var myArray = ["a","b","c"];

myArray.forEach(myCallbackFunction);

function myCallbackFunction(value) {
	console.log(value);
}


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

Tags: Javascript | foreach | JavaScript

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP