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

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.


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 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.


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.

Published on Apr 7, 2019

Tags: foreach | JavaScript

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.