JavaScript forEach | Looping Through an Array in JS

Last updated May 3rd, 2022
JavaScript's for each loop is a quick and easy way to iterate over an array. Used as an alternative to the for loop, it can make code more declarative and easy to read.

For many developers, JavaScript acts as introduction to the functional programming paradigm. And if you've never encountered callback functions before, the JavaScript for each function might look a little funny.

In this quick article, we're going to see how to iterate over an array of data using JavaScript's forEach function. We'll look at different ways to call it and discuss when to use it vs. the traditional for loop.

Using the JavaScript for each function

In JavaScript, the array object contains a forEach method. This means that on any array, we can call forEach like so:

let fruits = ['apples', 'oranges', 'bananas'];

fruits.forEach(function (item, index) {
  console.log(item, index)

This should print out the following.

apples 0
oranges 1
bananas 2

Let's explain how this works.

  1. We pass an anonymous function to the forEach method.
  2. Within that anonymous function, we include parameters to get access to the current item and the numerical index in the array that the item represents.

The function we provide to the forEach function has three parameters (two of which are optional).

  • (Required) The current element - Represents the current element
  • (Optional) Index - Returns the current index
  • (Optional) Array - Returns the entire array for each loop

Alternate ways to call it

Option 1: An anonymous function

The first of the alternate way to call this function is to utilize the anonymous function. This is what we just saw.

arr.forEach(function (item) { // Anonymous function
  // Write what you'd like to happen here

Option 2: Using arrow functions

The second option is to utilize an arrow function.

arr.forEach((item, index) => console.log(item, index))

Try this out. It allows you to write the loop on a single line.

Option 3: A callback function

The last option is to utilize a callback function, which is really just a function defined separately that we pass in as an argument to the forEach function.

let fruits = ['apples', 'oranges', 'bananas'];

function printPretty (item, index) {
  console.log(`${index} - ${item}`)


This should print out the following:

0 - apples
1 - oranges
2 - bananas

When to use the for loop vs. a for loop

Most of us first learn about loops the traditional way - you know, the loops with counters that get incremented? Like this:

let fruits = ['apples', 'oranges', 'bananas'];

for (let index = 0; i < fruits.length; i++) {

The truth is, you can use either traditional for loops or forEach loops. It doesn't matter.

However, using forEach loops results in code that looks a lot more declarative and easy to read, especially if you're dealing with nested loops (which I opt to try to avoid in the first place).


Liked this? Sing it loud and proud 👨‍🎤.


a month ago

There is still one performance benefit while using traditional for in case if you want to return early, for the next example the loop will be called 3 times only

const func = () => {
  for (let i = 0; i < 100; i += 1) {
    if (i === 3) {
      return i;

With foreach for the same example it will be called 100 times, so we will better go with find but it is another story

const func = () => {
    .from({ length: 100 }, (_, index) => index)
    .forEach((i) => {
      if (i === 3) {
        return i;

5 days ago

What about for ... of loop for arrays? It has advantages of returning early as well as working with elements of an array

Stay in touch!

About the author

Khalil Stemmler,
Developer Advocate @ Apollo GraphQL ⚡

Khalil is a software developer, writer, and musician. He frequently publishes articles about Domain-Driven Design, software design and Advanced TypeScript & Node.js best practices for large-scale applications.

View more in Web Development

You may also enjoy...

A few more related articles

Over $85 billion spent on fixing bad code [bootcamps, junior devs, JavaScript, and software design principles]
More and more money is being spent by companies on maintaining bad JavaScript code. Here's where I think our industry needs to cha...
TypeScript vs. JavaScript [Pros / cons]
TypeScript is arguably one of the best things to come to the JavaScript world helping developers comfortably create complex enterp...
How to Build a Related Posts Component with Gatsby.js
Here's how to build a "Related Posts" component for your Gatsby.js site.
Cleaner Code with Async / Await Tutorial
Asynchronous programming in JavaScript used to be difficult to write clean code with. Today we have options. You can write asynchr...

Want to be notified when new content comes out?

Join 10000+ other developers learning about Domain-Driven Design and Enterprise Node.js.

I won't spam ya. 🖖 Unsubscribe anytime.

Get updates