DEV Community

Cover image for Using "forEach" versus other loops in JavaScript
ctaylor0326
ctaylor0326

Posted on

Using "forEach" versus other loops in JavaScript

As a beginner software developer, one of the most common tasks you'll encounter is iterating over arrays and objects in JavaScript. One way to accomplish this is by using "for" statements, but there's another way that's often more efficient and easier to read: the "forEach" loop.

What is a "forEach" Loop?

A "forEach" loop is a built-in method in JavaScript that allows you to iterate over the elements of an array or the properties of an object. It takes a callback function as an argument and applies it to each element or property in the collection.

Here's an example of how to use a "forEach" loop to iterate over an array of numbers:

let numbers = [1, 2, 3, 4, 5];

numbers.forEach(function(number) {
  console.log(number);
});
Enter fullscreen mode Exit fullscreen mode

This code will output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

As you can see, the "forEach" loop applies the function to each element in the array, making it easy to iterate over the collection.

How Does it Compare to Other "For" Statements?

There are several other kinds of "for" statements you can use to iterate over arrays and objects in JavaScript, including "for", "for...in", and "for...of". Here's a quick overview of each:

"for" loop:

This is the most basic kind of loop, and it allows you to iterate over an array using a counter variable.

let numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}
Enter fullscreen mode Exit fullscreen mode

The loop starts with a variable "i" initialized to 0, and continues as long as "i" is less than the length of the numbers array. During each iteration of the loop, the console.log() method is used to output the element at the current index of the numbers array, accessed using bracket notation with numbers[i]. The loop then increments the "i" variable by 1 and continues with the next iteration.

The result of this loop would be the same as the forEach example above:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

"for...of" loop:

This loop allows you to iterate over the elements of an array or other iterable objects.

let numbers = [1, 2, 3, 4, 5];
for (let number of numbers) {
  console.log(number);
}
Enter fullscreen mode Exit fullscreen mode

In this example, the loop variable "number" is assigned the value of the first element in the numbers array, which is 1. The loop body then logs 1 to the console. The loop variable is then updated to the value of the next element in the array, which is 2. The loop body logs 2 to the console, and so on, until all of the elements in the numbers array have been processed.

Which would again generate:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

"for...in" loop:

This loop allows you to iterate over the properties of an object.

let person = {
  name: 'John',
  age: 30,
  gender: 'male'
};

for (let property in person) {
  console.log(`${property}: ${person[property]}`);
}
Enter fullscreen mode Exit fullscreen mode

During each iteration of the loop, the loop variable property is set to the name of the current property, and the console.log() method is used to output the property name and its corresponding value, accessed using bracket notation with person[property].

Which would return:

name: John
age: 30
gender: male
Enter fullscreen mode Exit fullscreen mode

While these "for" statements all accomplish the same goal of iterating over a collection, there are some key differences between them.

The "for" loop is the most basic kind of loop, and it's useful when you need to iterate over an array using a counter variable. However, it's less readable than the other kinds of loops and can be more prone to errors.

The "for...in" loop is useful for iterating over the properties of an object, but it can also include properties that are inherited from the object's prototype, which may not be what you want.

The "for...of" loop is the most modern of the "for" statements, and it's useful for iterating over the elements of an array or other iterable objects. However, it can't be used to iterate over object properties.

Why Use "forEach" Loops?

So why should you use "forEach" loops instead of other "for" statements? There are a few key reasons:

Readability:

"forEach" loops are more readable than other "for" statements because they use a callback function to specify the action to perform on each element or property.

Simplicity:

"forEach" loops are simpler than other "for" statements because you don't need to manually create a counter variable or worry about the syntax of the loop.

Efficiency:

"forEach" loops are often more efficient than other "for" statements because they're optimized for performance by the JavaScript engine. One reason for this is that "forEach" loops are often implemented using lower-level code than traditional "for" loops, which can make them faster. Additionally, "forEach" loops can be parallelized by the JavaScript engine, which means that the engine can run multiple iterations of the loop at the same time, further improving performance.

However, it's worth noting that there are some cases where traditional "for" loops may be more efficient than "forEach" loops. For example, if you need to exit the loop early based on a certain condition, a "for" loop with a break statement may be faster than a "forEach" loop.

Top comments (0)