DEV Community

Cover image for JavaScript `forEach()`: The Game-Changer Every Developer Needs!
Harish Kumar
Harish Kumar

Posted on • Edited on

JavaScript `forEach()`: The Game-Changer Every Developer Needs!

One of the most widely used utility functions for array traversal in JavaScript is the forEach() method. Here is a quick rundown of how the function works, its syntax, use cases, and some important things to keep in mind:

👉 Download eBook - JavaScript: from ES2015 to ES2023

.

Overview

The forEach() method runs a provided function once for each element in an array. This is quite cleaner and far more readable compared to the traditional for-loops for traversal across arrays.

Syntax

array.forEach(function(currentValue, index, array) {
  // code to execute for each element
}, thisArg);
Enter fullscreen mode Exit fullscreen mode
  • function(currentValue, index, array): A function to run on each element in this array. It takes three arguments:
    • currentValue: The current element being processed.
    • index (optional): The index of the current element being processed.
    • array optional: The array forEach was called upon
  • thisArg optional: Value to use as this when executing the callback function.

Example Usage

Here are some examples to showcase the use of forEach():

Basic Example

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

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

This will output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

Using Index and Array Parameters

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

numbers.forEach(function(number, index, array) {
  console.log('Index:', index, 'Value:', number);
  console.log(array);
});
Enter fullscreen mode Exit fullscreen mode

This will output each index and value pair, and print the entire array for each iteration.

Arrow Function

Using an arrow function makes the code more concise:

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

numbers.forEach(number => console.log(number));
Enter fullscreen mode Exit fullscreen mode

Practical Use Cases

  • Logging Each Element: forEach is often used to perform an action for every item in an array, such as logging to the console or modifying DOM elements.
  • Summing Values: Although reduce() is typically used for summing values, forEach can also be used to accumulate a sum.
  • Updating Elements: Apply a transformation or operation on each element of an array.

Important Details

  • No Return Value: forEach always returns undefined, so it should not be used if you need to derive a new array based on the original. Use map() instead in such cases.
  • Does Not Mutate the Array: Although forEach itself does not mutate the array, the function you provide can modify the elements of the array.
  • Break or Continue: You cannot break out of a forEach loop. If you need such control flow, consider using a traditional for loop or Array.prototype.every() or Array.prototype.some().

Comparison with Other Iteration Methods

  • for Loop: More verbose but offers complete control over iteration, including the ability to break out of the loop.
  • map(): Creates a new array with the results of calling a function on every element, while forEach does not return a new array.
  • filter(): Creates a new array with all elements that pass a test implemented by the provided function.
  • reduce(): Executes a reducer function on each element of the array, resulting in a single output value.

Conclusion

The forEach() method is a simple yet powerful way to iterate over arrays in JavaScript, making code cleaner and easier to read. It is ideal for cases where you want to execute a function on each element of an array without the need to return a new array or break out of the loop. However, if you need more control or different behaviour, consider other iteration methods such as for loops, map(), or reduce().

👉 Download eBook
javascript-from-es2015-to-es2023

Top comments (2)

Collapse
 
hkp22 profile image
Harish Kumar

Good work