Tony Lea

Javascript Foreach

Created April 9, 2019

The Javascript Foreach loop comes in very handy when you want to loop through an array of items. The loop will execute for each item in your array. Take a look at the following example of a Javascript Foreach loop:

// Create an array of groceries
var groceries = ['Milk', 'Eggs', 'Cheese'];

// Loop through each food item in the groceries array
groceries.forEach(function(food) {
	console.log(food);
});

And you would expect the following output:

Milk
Eggs
Cheese

This can also be accomplished with a traditional for loop, like so:

// Create an array of groceries
var groceries = ['Milk', 'Eggs', 'Cheese'];

// Loop through each food item in the groceries array
for( var i = 0; i < groceries.length; i++ ){
	console.log(groceries[i]);
}

You will get the same output with the traditional for loop; however, you can see that using the forEach loop it looks a lot nicer and makes your code more readable and clean. It's just a matter of preference, choose the one you like ;)


If you would like to learn the basics about Javascript be sure to checkout my free course on Javascript Basics. There are 9 simple to consume videos teaching you the basics of javascript in about a half hour.

Happy Coding!