JavaScript forEach() Method and Array Looping

The forEach method is a JavaScript Array method used to execute a function on each array element in order and was introduced in ECMAScript 2015.

A Simple Array Loop

One of the most basic approaches to looping over an array could look something like this:

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

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

// console output:
// "a"
// "b"
// "c"

This is a standard for loop, which takes an array of three characters and loops from the starting position of the array, 0, to the end position of the array, which in this case is 2, incrementing by one array index position through each loop iteration.

Note: In JavaScript, the first array index position always begins with 0, then 1, 2, and so on.  It's designed this way not to specify the index of the array, but rather the offset from the array's head.

Using the forEach Method to Loop Through an Array

To do the same thing with the forEach method, we simply just replace the for loop with some new code:

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

chars.forEach(char =>
console.log(char);
});

// console output:
// "a"
// "b"
// "c"

The output between the two methods is identical, but the behind-the-scenes functionality is a bit different. Instead of looping through an array one step at a time with an incremental index value like you would in a for loop, the forEach method specifies a callback function that is executed on each element of the array.

You're probably asking yourself, "So, what's so special about that?" Below are some things to consider when choosing between the two different kinds of loops.

forEach is Easier to Read

This is more of a personal preference item, but there is slightly less code involved with the forEach method.

Let's create a new, slightly more complex example than before by creating a new array of objects:

var foods = [
{ name: "Pizza" },
{ name: "Burger" },
{ name: "Taco" },
{ name: "Burrito" }
];

In a for loop, you would create an incremental index that's looped over until the end of the array has been reached:

for (var i = 0; i < foods.length; i++) {
var food = foods[i];
console.log(food.name);
}

With the forEach method, a temporary counter variable isn't necessary. You can define your variable name in your callback method and output it with less code:

foods.forEach(food => {
console.log(food.name);
});

Variable Scope is Retained Within the forEach Method

If you have a variable defined outside of the forEach method, the value of that variable is retained on the outside:

var nums = [0, 1, 2];
var num = 4;

nums.forEach(num => {
console.log(num);
});

// console output:
// 0
// 1
// 2

console.log(num);

// console output:
// 4

Breaking out of a forEach loop

You can easily break out of a standard for loop by using the break statement:

for (var i = 0; i < 2; i++) {
console.log(i);
break;
}

console.log(3);

// console output:
// 0
// 3

On the first loop iteration, 0 is output to the console, then the loop is terminated by using the break statement, which then outputs 3 outside of the loop.

In a forEach loop, you can't technically break out of the loop entirely. You can return in a loop, which will stop processing on the current array node and continue onto the next one. But the forEach method will always loop through the entire array until it reaches the end.

You could create a workaround by wrapping the loop inside a try/catch block and throwing an error:

var chars = ["a", "b", "c", "d", "e", "f"];

try {
chars.forEach((char) => {
console.log(char);

if (char == "c") {
throw "break";
}
});
}
catch(err) {}

console.log("g");

// console output:
// a
// b
// c
// g

This code tells the forEach method to loop through array chars until it finds the c character. Once it does, an error is thrown and the loop is then terminated.

Conclusion

The performance differences between for loops and forEach methods are close to none. It comes down to the types of data you're dealing with, readability, and overall personal preference.