JavaScript Array forEach() Method

JavaScript Array forEach() Method

JavaScript is a synchronous and single-threaded language, which provides you various ways to iterate elements over an array. One of them is forEach() method. If you ever need to iterate elements over an array without creating a new array, then the forEach() method is a great choice. In this blog, we will get a deep understanding of its syntax, usage, limitations, and alternatives to help you fully understand the forEach() in JavaScript.

Table of Contents:

forEach() method in JavaScript allows you to execute a function once for each element in an array. Using the forEach() loop in your code doesn’t return a new array, and if it starts once, it cannot be stopped. This makes them ideal for performing actions like modifying the DOM and making API calls.

Why Use forEach()

  • It has simple and readable syntax
  • It is good if you want to execute a function on array elements.
  • It eliminates the need of for loop in some cases.

Syntax And Parameters

Here is the way of writing forEach() loop in javascript.

array.forEach(callback(element, index, array), thisValue);

The syntax written above is the general syntax of writing forEach() loop in javascript. There are a total of five parameters. Let’s discuss each of them:

Parameter Optional Description
callbackNoIt is a function executed once for each element of the array.
elementNoThe current array element for which iteration is going on.
indexYesIt is the index of the current element.
arrayYesThe array forEach() is called on.
thisValueYesIt specifies the value that will be used in the callback function.

Examples for forEach() Method in JavaScript

Here are some examples to understand the forEach() loop in JavaScript.

Example 1: Basic code for printing array elements.

Javascript

Output:

Basic code for printing array elements Output

Explanation: In this code, you’re printing array elements by using the forEach() loop. This will iterate through every single element in your array and one by one print those elements.

Example 2: Copying elements of an array to a new array

Javascript

Output:

Copying elements of an array to a new array Output

Explanation: Copying elements of an array to a new array is also a simple task. As in the above example you see we use the same forEach() loop but now this time .push() method of javascript is used to put elements in the new array.

Example 3: Calculate the cube of each number in the array.

Javascript

Output:

Calculate the cube of each number in the array Output

Explanation: In the above code, the forEach() method iterates over all the elements of the array, computes the cube by the given formula, and then displays the result using the  console.log() function.

Example 4: Using thisValue Parameter

Javascript

Output:

Using thisValue Parameter Output

Explanation: In this example, we are using this parameter that is optional when you use the forEach() loop.

Here, this.multiplier value is 2. Every time in each iteration 2 is multiplied by numbers in the array and produces the above output.

Limitations of forEach() method

  1. No Break or Continue: Unlike for() loops, you are not able to use the break and continue keywords in forEach() loop. In other words, forEach() cannot be stopped or skipped.
  2. No Return Value: it returns undefined always. So you didn’t make a function chain if you’re using it.
  3. Not Suitable for Asynchronous Operations: It doesn’t wait for async operations to complete. forEach() doesn’t handle async/await well.

Alternatives of forEach() Method

There are fewer alternatives to forEach() loop that you will use based on your choice and convenience:

1. map() method

map() method is used if you have to create a new array instead of modifying the original array.

Example:

Javascript

Output:

map() method Output

Explanation: The map() method iterates over an array and calculates the square of each element then puts those calculated values in the new array and prints that array.

2. for..of loop

for..of loop is another looping method in JavaScript. As you know, forEach() cannot be stopped or continued. But if you want to use a break and continue inside the loop, then for..of loop is another choice for you.

Example:

Javascript

Output:

for..of loop Output

Explanation: In this example, we are using the for..of loop. It will print the number till 2 when (num==3), then it will break the loop, and the number after that will not be printed.

Comparison Between forEach() and Other Looping Methods

Here is the comparison between forEach and the other looping methods. This will help you to choose the right looping method:

Methods Description Important Note
forEach()It iterates over an array and executes the callback function once for each element.It doesn’t return a new array. Make changes in the original array.
map()It iterates over an array, applies a function to each element, and returns a new transformed array.Unlike forEach(), it returns a new array and doesn’t modify the original array.
for…ofIterates over iterable objects like arrays, strings, Maps, Sets, etc.Supports await inside async functions and is more readable than the forEach() in some cases.
for loopA traditional loop that uses a counter to iterate elements of an array.To provide more control over iterations, you can use keywords like break and continue inside it.

Browser Compatibility

forEach() is supported in all modern browsers, including Chrome, Firefox, Safari, Edge, and Opera. But if you’re working with an older browser like Internet Explorer, the forEach() method may not be supported or may not work efficiently.

Conclusion

The forEach() method is powerful for iterating over arrays in javascript. Because it’s easier to write and read. However, it has some limitations, such as the inability to stop or continue and return a new array. Thus other methods are also there like map(), for…of, or reduce() that may be more suitable in place of forEach().

JavaScript Array forEach() Method – FAQs

1. How does forEach loop through an array in JavaScript?

forEach() applies a callback function to each element in an array. And executing it one at a time.

2. Which loop is faster in JavaScript?

The for() loop is generally faster than other loops because it has less function call overhead.

3. How to loop over an array in JS?

You can use any of the looping methods like for(), forEach(), for..of, and more.

4. How do you use forEach() with an array?

Call forEach() on an array and pass a function as an argument arr.forEach(item => console.log(item)).

5. Is forEach() faster than the for loop?

No, for() loops are faster due to fewer function calls.

6. How to iterate backward through an array of JavaScript?

You can do this by using a for loop:

Example:


const arr = [1, 2, 3, 4];

for (let i = arr.length - 1; i >= 0; i--) {

    console.log(arr[i]);

}

Output:

backward through an array of JavaScript Output

Explanation: Run for() loop in a backward direction and print the elements one by one.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner