Table of contents
1.
Introduction
2.
What is forEach method in JavaScript?
2.1.
Syntax
2.2.
Parameters
2.3.
Return Value
3.
forEach() Examples in JavaScript
3.1.
How to use the currentElement Argument
3.2.
Javascript
3.3.
How to use the index Argument
3.4.
Javascript
3.5.
How to use the array Argument
3.6.
Javascript
3.7.
How to Add All Values in An Array of Numbers with forEach()
3.8.
Javascript
3.9.
How to Use Conditionals in a forEach() Callback Function
3.10.
Javascript
4.
Comparing forEach() with a for Loop
4.1.
Example (forEach):
4.2.
Javascript
4.3.
Example (for loop):
4.4.
Javascript
4.5.
Break out and Continue in a Loop
4.5.1.
Example (for loop with break):
4.6.
Javascript
4.7.
Array with Missing Elements
4.8.
Javascript
5.
Limitations of forEach() Method
6.
Advantages of foreach method
7.
Disadvantages of foreach method
8.
Future of JavaScript forEach:
9.
Frequently Asked Questions
9.1.
How to get forEach value in JavaScript?
9.2.
How can one use forEach () method?
9.3.
What is forEach method and map method in JavaScript?
10.
Conclusion
Last Updated: Dec 23, 2024
Easy

JavaScript Array forEach() Method

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

JavaScript, the cornerstone of web development, boasts a myriad of methods enhancing the ease and efficiency of coding practices. Among these, the forEach method shines bright, offering a simplified approach to iterate over arrays. 

javascript foreach

This article aims to delve into the abyss of the forEach method, elucidating its functionality, advantages, disadvantages, and practical applications, even peering into its future in the ever-evolving realm of JavaScript.

What is forEach method in JavaScript?

The forEach method in JavaScript is an array iteration method used to execute a provided function once for each element in an array. It doesn't create a new array but allows you to perform an action on each element. 

Syntax

Here's the basic syntax:

arr.forEach(callback(element, index, array), thisArg)

 

In this syntax, arr is the array on which forEach is called, callback is the function that gets executed on each element of the array, and thisArg is an optional parameter to pass the value of this.

Parameters

The following are the parameters passed in forEach method in JavaScript:

ParameterDescription
elementThe current element being processed in the array.
indexThe index of the current element being processed.
arrayThe array that forEach is being applied to.

Return Value

forEach doesn't return anything. It is primarily used for its side effects.

forEach() Examples in JavaScript

Let us see few examples of forEach() method in Javascript:

How to use the currentElement Argument

The currentElement argument in forEach() represents the element currently being processed. You can use it to perform operations on each item.

Example:

  • Javascript

Javascript

const numbers = [1, 2, 3, 4, 5];
numbers.forEach((currentElement) => {
console.log(currentElement);
});
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

1
2
3
4
5

How to use the index Argument

The index argument provides the position of the currentElement within the array. It helps in operations needing element positions.

Example:

  • Javascript

Javascript

const fruits = ['apple', 'banana', 'cherry'];
fruits.forEach((currentElement, index) => {
console.log(`Index ${index}: ${currentElement}`);
});
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

Index 0: apple
Index 1: banana
Index 2: cherry

How to use the array Argument

The array argument represents the entire array being processed. It can be used for operations involving the whole array.

Example:

  • Javascript

Javascript

const numbers = [10, 20, 30];
numbers.forEach((currentElement, index, array) => {
console.log(`Array: ${array}, Element: ${currentElement}`);
});
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

Array: 10,20,30, Element: 10
Array: 10,20,30, Element: 20
Array: 10,20,30, Element: 30

How to Add All Values in An Array of Numbers with forEach()

To sum all values in an array, initialize a total variable outside forEach() and accumulate values within the callback.

Example:

  • Javascript

Javascript

const numbers = [5, 10, 15];
let sum = 0;
numbers.forEach((currentElement) => {
sum += currentElement;
});
console.log(sum);
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

30

How to Use Conditionals in a forEach() Callback Function

You can use conditionals inside the forEach() callback to perform actions based on specific criteria.

Example:

  • Javascript

Javascript

const numbers = [1, 2, 3, 4, 5];
numbers.forEach((currentElement) => {
if (currentElement % 2 === 0) {
console.log(`${currentElement} is even`);
} else {
console.log(`${currentElement} is odd`);
}
});
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

1 is odd
2 is even
3 is odd
4 is even
5 is odd

Comparing forEach() with a for Loop

forEach() is used for iterating over arrays, while a for loop offers more control, such as breaking or continuing iterations.

Example (forEach):

  • Javascript

Javascript

const numbers = [1, 2, 3];
numbers.forEach((number) => {
console.log(number);
});
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

1
2
3

Example (for loop):

  • Javascript

Javascript

const numbers = [1, 2, 3];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

1
2
3

Break out and Continue in a Loop

forEach() doesn’t support break or continue to exit or skip iterations. Use a for loop for such functionality.

Example (for loop with break):

  • Javascript

Javascript

const numbers = [1, 2, 3, 4];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === 3) break;
console.log(numbers[i]);
}
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

1
2

Array with Missing Elements

forEach() iterates over all elements, including those with undefined values. Sparse arrays have missing indices but still iterate with forEach().

Example:

  • Javascript

Javascript

const array = [1, , 3];
array.forEach((currentElement, index) => {
console.log(`Index ${index}: ${currentElement}`);
});
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

Index 0: 1
Index 2: 3

Limitations of forEach() Method

  1. The `forEach()` method does not return a new array. It simply executes the provided function once for each element in the array.
  2. There is no way to stop or break the iteration of the `forEach()` loop other than by throwing an exception. If you need to break out of the loop early, you may consider using a simple `for` loop instead.
  3. The `forEach()` method always iterates over every element in the array, skipping only empty slots in sparse arrays. It does not iterate over deleted elements or elements that have never been assigned a value.
  4. The `forEach()` method does not wait for promises. If you need to perform asynchronous operations on each element, consider using `Promise.all()` or `for...of` loop with `async/await`.
  5. The `forEach()` method does not allow you to specify the value of `this` to be used when executing the callback function. If you need to use a specific `this` value, you can use the `thisArg` argument of the `forEach()` method or use an arrow function as the callback.

Advantages of foreach method

  • Simplified Iteration: forEach offers a clean, concise way to iterate over arrays, enhancing code readability.
     
  • Access to Array Elements: It provides access to the current element, its index, and the entire array during iteration, facilitating a broad range of operations within the callback function.
     
  • No Need for a Counter: Unlike traditional loops, forEach eliminates the need for a counter variable, reducing the chance of errors.

Disadvantages of foreach method

  • No Break Control: Unlike traditional loops, forEach doesn’t support break or continue statements, which can be a limitation when seeking to exit the loop prematurely.
     
  • Performance: forEach can be slower than traditional for loops, especially in older JavaScript engines.
     
  • Not Chainable: Unlike other array methods like map or filter, forEach doesn’t return a value that can be chained.

Future of JavaScript forEach:

The forEach method is here to stay, with potential enhancements in future ECMAScript versions that could bolster its performance or provide more control over iteration.

Frequently Asked Questions

How to get forEach value in JavaScript?

To get the forEach value in JavaScript, use the element parameter within the callback function. It represents the current item being processed. For example: array.forEach((element) => { console.log(element); });.

How can one use forEach () method?

Use forEach by passing a callback function to perform an action on each element of an array.

What is forEach method and map method in JavaScript?

Both forEach and map are array methods in JavaScript. forEach executes a provided function for each array element, while map creates a new array by applying a function to each element.

Conclusion

The forEach method in JavaScript is a potent tool for array iteration, offering a blend of simplicity and functionality. While it has its set of limitations, the advantages and practical applications it brings to the table make it a worthy contender in a developer's arsenal. As JavaScript continues to evolve, the forEach method is likely to retain its relevance, continuing to simplify array iteration for developers across the globe.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass