forEach() in JavaScript

Nilesh Saini
May 7, 2022

--

Concise explanation of forEach() method in Js

Photo by Katie Moum on Unsplash
  1. Iterates through an array.
  2. Runs a callback function on each value in the array.
  3. Returns undefined.

Note: forEach always returns undefined.

How does it work?

Parameters:

  • Callback Function: Function to execute on each element. It is called with the following arguments:
  • Value: Current element being processed in the array.
  • Index: index of the element in the array.
  • Array: The complete array on which forEach method is called.
  • thisArg: Value to use as this when executing the callback function.

Note: In the callback function we don’t always have to use the three parameters (Value, Index, Array), Use whichever ones you need, just remember the order is important.

Note: thisArg parameter is optional too.

Examples:

  1. Given an array, print all the values in the console using forEach().

2. Return the sum of all elements in the array using forEach().

--

--

Nilesh Saini
Nilesh Saini

Written by Nilesh Saini

Web Developer/ Front-end engineer who loves solving Rubik's Cube