JavaScript forEach() Method: Ultimate Guide (Examples & Theory)

In JavaScript, you can use the built-in Array.forEach() method to act upon each element in the array.

For instance, given an array of numbers, let’s print all the values one number at a time:

const numbers = [1, 2, 3, 4, 5]

numbers.forEach(num => console.log(num))

Output:

1
2
3
4
5

The forEach() method does not create a new array. Instead, it just operates for each element.

If you want to create a new array, you need to use the map() method, which is very similar to the forEach() method.

This is a comprehensive guide on the Array.forEach() method in JavaScript.

  • You are going to learn how to use the forEach() method instead of for loops.
  • You will learn what are callback functions, inline callbacks, and arrow functions.
  • The theory in this guide is backed up with great examples.

Let’s jump into it.

Why Use the forEach() Method?

In JavaScript, you can use the forEach() method to loop over arrays.

This method can make your code short.

The forEach() method allows you to replace lengthy loops with shorter looping expressions.

Let’s make a comparison with a for loop and forEach() function.

For Loops in JavaScript

In JavaScript, a for loop can be used to loop through an array.

Let’s see an example of using a for loop to print out the values of an array:

const numbers = [1, 2, 3, 4, 5]

for (const number of numbers) {
    console.log(number)
}

Output:

1
2
3
4
5

This for loop gets the job done.

However, one could argue this approach is more complex than it needs to be.

Instead of using a for loop, you can use the forEach() method to compress the code while maintaining readability.

The forEach() Method

In JavaScript, you can use the forEach() method to operate for each element in the array.

Let’s replace the for loop from the previous example with the forEach() method.

Here is how it looks:

const numbers = [1, 2, 3, 4, 5]
numbers.forEach(num => console.log(num))

Output:

1
2
3
4
5

As you can see, this looks cleaner and is shorter than the for-loop approach.

You now understand why the forEach() method is useful in JavaScript.

Next, you are going to learn how the forEach() method works in detail.

The forEach() Method in JavaScript

In JavaScript, you can use Array.forEach() method to call a function for each element in an array.

Let’s start with the syntax of the forEach() method.

The Syntax

There are many combinations of how to use the forEach() method.

You should choose an approach based on what you are trying to accomplish.

Here is a list of different syntaxes for calling the forEach() method:

// 1. forEach with callback functions
forEach(callbackFn)
forEach(callbackFn, thisArg)

// 2. forEach with inline callback functions
forEach(function(element) { /* action */ })
forEach(function(element, index) { /* action */ })
forEach(function(element, index, array){ /* action */ })
forEach(function(element, index, array) { /* action */ }, thisArg)

// 3. forEach with arrow functions
forEach((element) => { /* action */ })
forEach((element, index) => { /* action */ })
forEach((element, index, array) => { /* action */ })

Let’s choose the full approach for further inspection:

forEach(function(element, index, array) { /* action */ }, thisArg)

In this expression:

  • function is a callback. It is called for each element of the array. The callback function takes the following arguments:
    • element is the current element we are calling the function for.
    • index is optional. It is the index of the current element.
    • array is also optional. It is the array on which the forEach() method was called.
  • this argument is optional. It is the value that is used as ‘this‘ inside the callback when operating on the array elements.

More often than not you only need to specify the element argument. So the forEach() call looks significantly simpler.

But I am going to show you an example of those “extra” parameters at the end of this guide.

Before learning how to use forEach(), you need to learn what is a callback function. It was mentioned a couple of times but there is a chance you have no idea what it means.

Callbacks in JavaScript

In JavaScript, a callback function is a function passed as an argument to another function.

For instance, when you use the forEach() method, you pass it another function that is called for each element in the array.

The term “callback” originates from asynchronous JavaScript. You can use callbacks to call back when an asynchronous task has been completed.

The built-in setTimeOut() function is a great example of using callbacks. The setTimeOut() function takes two arguments:

  • A function to execute. This is a callback function as it is a function inside a function.
  • A time interval after which the callback can be executed.

For instance:

setTimeout(() => {
    console.log("Hi, it is me!")
}, 1000);

After a second delay, the callback calls you back:

"Hi, it is me!"

Now you should have a basic understanding of what the callback function means.

But this article is not about async JavaScript. So let’s get back to the forEach() method.

The Array.forEach() Method with Callback Functions

The most basic way to use the forEach() method is by passing it a callback function.

For instance, let’s print an array of numbers, such that each number is squared.

const numbers = [1, 2, 3, 4, 5]

function printSquared(number) {
    console.log(number * number)
}

numbers.forEach(printSquared)

Output:

1
4
9
16
25

As you can see, the printSquared function is defined separately. This function takes a number argument and prints a squared version of it.

You then pass this function as a callback to the forEach() method.

You do not need parenthesis in the forEach() because it only needs the name of the function to call.

After this, it knows how to take care of the rest.

In other words, the forEach() method:

  • Takes whatever function name was passed to it.
  • Picks an element from an array.
  • Calls the function on the element.

Now you know how to use forEach() with callbacks.

But this is not your typical way of calling the forEach() method.

More often than not, you are going to use one of these:

  • An inline callback function.
  • An arrow function.

Let’s take a look at what this means.

The Array.forEach() Method with Inline Callback Functions

The word “inline” refers to a function used in the line of code where it is implemented.

In the previous example, you called the forEach() method with a callback function that was defined separately.

However, you can also define the callback directly into the forEach() method call.

This is an inline callback function.

For example, let’s print an array of numbers squared:

const numbers = [1, 2, 3, 4, 5]

numbers.forEach(function(number) {
    console.log(number * number)
})

Output:

1
4
9
16
25

As you can see, now there is no separate printSquared function.

Instead, it is defined directly into the forEach() call.

But why do this?

An inline callback is good if you only need the functionality once.

The above example demonstrates this perfectly.

You only need the squaring functionality once. So it is not clever to leave a useless function hanging around in the codebase.

To make the inline callbacks even shorter, you can sometimes use arrow functions.

The Array.forEach() Method with Arrow Functions

An arrow function is a short alternative for a function expression.

Notice that you cannot always use an arrow function. Check the arrow function limitations here if you like.

An arrow function can be used with these syntaxes:

param => expression

(param1, param2) => expression

param => {
    multiple_expressions
}

Compare these to the regular function expression:

function name(param1, param2) {
    expressions
}

You can benefit from using an arrow function in the forEach() method. This is because it can make the code even more concise.

For instance, let’s square an array of numbers using an arrow function:

const numbers = [1, 2, 3, 4, 5]

numbers.forEach(number => console.log(number * number))

Output:

1
4
9
16
25

Wonderful!

Now you have seen the most common ways to use the forEach() method.

It is time to take a look at the optional arguments forEach() method takes.

  • index
  • array
  • thisArg

These are not usually needed, but it never hurts to understand how they work.

Other forEach() Method Arguments

As you learned earlier, the forEach() method can take up to 4 arguments:

forEach(function(element, index, array) { /* action */ }, thisArg)

In the previous chapter, you only saw examples with the element argument.

But sometimes you might need to be able to use the other arguments as well.

Let’s see two examples.

forEach(function(element, index, array))

When calling the forEach() method, you can make the callback function accept the current element of the array.

In addition to this, you can also access the current element’s index and the array itself.

For example, given an array of names in a queue, let’s print the following information to the console:

  • The current position of each person in the queue.
  • Who comes after each person.

To pull this off, you need to access the current element, its index, and the array itself.

Here is how it looks in the code:

const queue = ["Alice", "Bob", "Charlie"]

const queueInfo = queue.forEach(function(name, index, arr) {
    const next = index + 1 < arr.length ? arr[index + 1] : "no one"

    console.log(`${name} is at position ${index + 1}, the next is ${next}`)
})

Output:

"Alice is at position 1, the next is Bob"
"Bob is at position 2, the next is Charlie"
"Charlie is at position 3, the next is no one"

Next, let’s see how to override this property by specifying the second argument thisArg to the forEach() method.

forEach(callback, thisArg)

The forEach() method takes an optional second parameter thisArg.

It lets you override this within the scope of the callback.

Doing this is useful if you want to reuse the callback in different contexts when calling the forEach() method.

Example. Given an array of x,y coordinates let’s transform them according to the screen size of the current view:

let posData = [[50, 100], [200, 300]]

const defaultSize = { width: 320, height: 480 }

function transform(coords) {
    coords[0] = coords[0] * this.width / defaultSize.width
    coords[1] = coords[1] * this.height / defaultSize.height
}

posData.forEach(transform, { width: 1280, height: 1920 })

console.log(posData)

Output:

[[200, 400], [800, 1200]]

In this piece of code, thisArg is a window object { width: 1280, height: 1920 }.

As you can see, the original coordinates were transformed to correspond to the same position in a differently-sized view.

Better yet you can do this in any context you like.

Example Use Cases for forEach() Method

Let’s take a look at some common examples of how to use the forEach() method in your code.

Example 1: Call a Function for Each Element in an Array

You can use the forEach() method to operate each element of the array.

This is something you already saw a bunch of times in this guide.

But practice makes perfect, so let’s see one more example.

For instance, let’s print an array of strings in the upper case:

const names = ["Alice", "Bob", "Charlie"]

names.forEach(name => console.log(name.toUpperCase()))

Output:

"ALICE"
"BOB"
"CHARLIE"

Example 2: Reformat Array Objects

Similar to a for loop, the forEach() method can be used to modify objects in an array.

For example, given an array of user objects, let’s transform the string values to uppercase:

const users = [
    { name: 'Bob',     hobby: 'Jogging' },
    { name: 'Charlie', hobby: 'Gym' },
    { name: 'Alice',   hobby: 'Golf' }
]

users.forEach(user => {
    user.name = user.name.toUpperCase()
    user.hobby = user.hobby.toUpperCase()
})

console.log(users)

Output:

[{
  hobby: "JOGGING",
  name: "BOB"
}, {
  hobby: "GYM",
  name: "CHARLIE"
}, {
  hobby: "GOLF",
  name: "ALICE"
}]

As you can see, we were able to modify the original array with the forEach() method.

Example 3: Borrow forEach() Method from Array to String

The forEach() method belongs to the Array data type.

Thus, you cannot call String.forEach().

However, you can extract this method from the Array and use it on a string.

This is possible by using the .call() method.

The .call() method lets you use the context of one object with another.

In this case, you can use the forEach() method that belongs to an Array on a String.

For example, let’s print each character of a string in the upper case:

const name = "Sam"

Array.prototype.forEach.call(name, letter => console.log(letter.toUpperCase()))

Output:

"S"
"A"
"M"

This works as if the forEach() method belonged to a string even it does not.

Next, let’s take a look at a bunch of common questions related to using the forEach() method in JavaScript.

forEach() Common Tasks/Questions

Last but not least, let’s go through the most sought-after questions related to the forEach() method in JavaScript.

forEach() with ‘break’ or ‘continue’ Statement

You cannot use break or continue statements in the forEach() method.

The only way to break the forEach() loop from executing is by throwing an exception.

If you want to use break or continue statements, pick an approach that supports early termination.

For instance, you can use:

  • A for loop
  • for…of loop
  • for…in loop

forEach() with Index

You can access the index of the array element in the forEach() method.

The callback function passed into the forEach() method takes an optional index argument.

If this argument is specified, the forEach() function has access to the index of each argument.

For instance:

const queue = ["Alice", "Bob", "Charlie"]

const queueInfo = queue.forEach(function(name, index, arr) {
    console.log(`${name} is at position ${index + 1}`)
})

Output:

"Alice is at position 1"
"Bob is at position 2"
"Charlie is at position 3"

Call forEach() on Objects

You cannot call forEach() on objects. In JavaScript, objects do not have access to the Array.prototype methods.

But in a way, you can still call forEach() on an object. To do this:

  • Convert the object’s keys to an array with the Object.keys() method.
  • Call .forEach() on the array of keys.
  • Access the values with the key.

For example:

const data = { name: "Alice", age: 32, hobby: "Golf" }

Object.keys(data).forEach( key => {
    console.log(`${key}: ${data[key]}`)
})

Output:

"name: Alice"
"age: 32"
"hobby: Golf"

Whether this is any cleaner than using a regular for loop or not is up for debate.

However, this shows you how to do it.

forEach() vs map()

The forEach() method reminds the map() method.

The key difference is that:

  • The forEach() method does not return a new array. Instead, it calls a function for each element in the array.
  • The map() method creates a new array based on the results of calling a function for each element in the source array.

Conclusion

Today you learned how to use the forEach() method in JavaScript.

To recap, the forEach() method can be used to operate each element in an array.

The forEach() method does not return a new array. Instead, it just calls a function for each element in the array.

The forEach() method works by calling a callback function on each array element.

Thanks for reading.

Happy coding!

Scroll to Top