DEV Community

Ali Taha Shakir
Ali Taha Shakir

Posted on • Updated on

forEach() Array Method

JavaScript provide us with several built in functions to work with arrays which are know as Array Methods. Lets take a closer look at JavaScript forEach() method.

The forEach() method executes a callback function for each element of array. That callback function accepts between one and three arguments:

  • Current Value (required) – The value of the current array element being processed in loop
  • Index (optional) – The current element’s index number
  • Array (optional) – The array forEach() was called upon

Considering that we have the following array below:

const numbersArray = [1, 2, 3, 4, 5];
Enter fullscreen mode Exit fullscreen mode

Lets apply forEach() method to numbers array, you need a callback function (or anonymous function):

numbersArray.forEach(function() {
    // code
});
Enter fullscreen mode Exit fullscreen mode

The function will be executed on each element of the array. It requires the current value parameter which represents the element of an array which is currently being processed in loop:

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

Alt Text

This is the minimum required syntax to run forEach() method.

Alternatively, you can use the ES6 arrow function representation for simplifying the code:

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

If you enjoyed this post please share, and follow me on DEV.to or Twitter if you would like to know as soon as I publish a post! 🔥

Top comments (0)