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
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
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
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
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
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
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
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
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
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
- The `forEach()` method does not return a new array. It simply executes the provided function once for each element in the array.
- 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.
- 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.
- 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`.
- 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 DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.