DEV Community

Cover image for forEach The Quiet Powerhouse
MaettaToo
MaettaToo

Posted on

forEach The Quiet Powerhouse

As a beginner JavaScript student I was very intimidated by the forEach() method. Now as I have progressed in my journey in learning JavaScript I have a deep appreciation of forEach().

What is forEach()

In layman’s terms it is a method to iterate over an array similar to .map() and a for loop but with significant differences.
.

Syntax:

array.forEach(callbackFn)

forEach(callbackFn)
forEach(callbackFn, thisArg)
Enter fullscreen mode Exit fullscreen mode
  • array(required): array to be iterated over
  • callbackFn (required): A function to execute for each element in the array.

Callback Parameters

  • element(required): The current element being processed in the array.
  • index(optional):The index of the current element being processed in the array.
  • array(optional): The array forEach() was called upon.
  • thisArg(optional): A value to use as this when executing callbackFn .

How does forEach work

JavaScript's forEach() method iterates over the input array elements. It passes each element to the provided callback function in ascending-index order.

let sum = 0;

const demo = [1, 2, 3, 4];// array to be iterated over 

demo.forEach((currentElement) =>{//array.forEach((currentElement))=>{}
  sum += currentElement//function code to invoked on each element 
})

console.log(sum);// 10
Enter fullscreen mode Exit fullscreen mode

Things to Remember

  • The return value of this method is always undefined.
  • This method may or may not change the original array provided as it depends upon the functionality of the argument function.

Why is it a quiet powerhouse?

The beauty of forEach is its versatility and cleanliness.

Versatility

The forEach() approach can be used in many different ways.

  • As mentioned above it does not return a new array or alter the original array. That makes it useful for operations like logging or modifying elements in place
let multiples = [];

const demo = [1, 2, 3, 4];// array to be iterated over 

demo.forEach((currentElement) =>{//array.forEach((currentElement))=>{}
   multiples.push(currentElement*=2); //function code to invoked on each element 
})
console.log(multiples)//[2, 4, 6, 8]

Enter fullscreen mode Exit fullscreen mode
  • The function in the forEach doesn’t have to be anonymous. It can be declared separately and then passed into forEach.
const demo = [1, 2, 3, 4];// array to be iterated over

let sum = 0;// variable to hold results

const addSum = (num)=>{// named function
  sum += num
  }
demo.forEach(addSum);//array.forEach(callback)

console.log(sum);//10
Enter fullscreen mode Exit fullscreen mode
  • It can access indices alongside values using the second parameter of the callback function.
const animals = ["cat", "dog", "rabbit"];

animals.forEach((animal, index) => {
  console.log(`Index ${index}: ${animal}`);
});
//"Index 0: cat"
//"Index 1: dog"
//"Index 2: rabbit"
Enter fullscreen mode Exit fullscreen mode
  • It can access the full array using the third parameter of the callback function. This is useful when you don't have an existing variable that refers to the array.
const animals = ['cat','monkey', 'bird'];

animals.forEach((animal, index, arr) => {
  console.log(`Value: ${animal}, Array: ${arr}`);
});
//"Value: cat, Array: cat,monkey,bird"
//"Value: monkey, Array: cat,monkey,bird"
//"Value: bird, Array: cat,monkey,bird"
Enter fullscreen mode Exit fullscreen mode

Cleanliness

The forEach() approach is shorter and easier to understand.
It uses less code, is easier to read, and is less likely to have errors.

  • Uses less code- logic is defined directly within the forEach() callback, making the code self-contained and easy to maintain.
  • Easier to read- provides a more concise and readable way to iterate over arrays, especially compared to traditional loops.
  • Less likely to have errors- doesn’t need to initialize variables, set loop conditions, or increment counters. This reduces the likelihood of errors.
let sum = 0;

const demo = [1, 2, 3, 4];// array to be iterated over 

for(let i = 0; i< demo.length; i++){//iterate over array
 sum = demo[i] += sum//add all numbers in the array
}
console.log(sum);//10
Enter fullscreen mode Exit fullscreen mode
let sum = 0;

const demo = [1, 2, 3, 4];// array to be iterated over 

demo.forEach((currentElement) =>{//array.forEach((currentElement))=>{}
  sum += currentElement//function code to invoked on each element 
})

console.log(sum);// 10
Enter fullscreen mode Exit fullscreen mode

Limitations

  • Not Chainable- forEach() always returns undefined and is not chainable.
const tvShow = ['I','Love','Lucy'];

const tv = tvShow.forEach((word) => word += word );
console.log(result); // undefined
Enter fullscreen mode Exit fullscreen mode
  • callbackFn is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.
  • The forEach() method is generic. It only expects the this value to have a length property and integer-keyed properties.
  • Cannot Break or Continue-There is no way to stop or break a forEach() loop other than by throwing an exception. Early termination may be accomplished with looping statements
const numbers = [5, 10, 15, 4, 7];

numbers.forEach((num) => {
  if (num > 5) {
    return; // Only exits the current callback, not the loop
  }
  console.log(num);
});//5, 4
Enter fullscreen mode Exit fullscreen mode
  • Not Suitable for Asynchronous Operations- forEach() expects a synchronous function — it does not wait for promises. Make sure you are aware of the implications while using promises (or async functions) as forEach callbacks
const ratings = [5, 4, 5];
let sum = 0;

const sumFunction = async (a, b) => a + b;

ratings.forEach(async (rating) => {
  sum = await sumFunction(sum, rating);
});

console.log(sum);
// Naively expected output: 14
// Actual output: 0

Enter fullscreen mode Exit fullscreen mode

Conclusion

forEach is truly a powerhouse for creating clean and functional code. forEach is great for performing an operation on each array element. It streamlines code and makes it easier to read. Its versatility and simplicity allows many different applications. It is truly an underrated wonder.

Check these sources
mdn web docs

JavaScript ES6: The forEach() Helper

The Complete Guide to JavaScript’s "forEach" Method

Difference between forEach() and map() loop in JavaScript

Top comments (0)