DEV Community

Ali Taha Shakir
Ali Taha Shakir

Posted on • Edited on

2

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! 🔥

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay