Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 52

Iterating with forEach

This lesson is built with resources from youtube.com, gomakethings.com and 1 more site.

Hello! Welcome back to our exploration of JavaScript's powerful array methods.

In our last lesson, we mastered splice(), a surgical tool for mutating an array by adding, removing, or replacing elements. That method was all about direct manipulation. Now, we're shifting our focus to one of the most common and fundamental tasks in programming: performing an action on every single item in a collection.

This lesson introduces the forEach() method. Instead of manually setting up a for loop with counters and conditions, forEach() provides a clean, modern, and more readable way to iterate through an array. This is a foundational method that you will use constantly as you build applications.

By the end of this lesson, you will be able to iterate over arrays using the forEach() method to execute a function for each element, a key skill for working with data in JavaScript.

From Manual Loops to Declarative Iteration

Before we had convenient methods like forEach(), the standard way to loop through an array was using a for loop, which you'll remember from an earlier module. You had to manually manage the state: initialize a counter, check a condition, and increment the counter.

To understand why forEach() is so useful, it helps to see the problem it solves. This video provides an excellent transition from the old way (for loop) to the new way (forEach()).

Array forEach Method in JavaScript | JavaScript Array Methods | Beginners tutorial

Watch this first section from the 'Array forEach Method' video by Code Explained. It starts with a standard for loop and refactors it, showing how forEach simplifies the entire process by abstracting away the manual counter and condition checking.

Watch from the beginning until 03:40. Pay close attention to how the for loop's logic—initializing, checking, and incrementing an index—is handled automatically by the forEach method.

As the video demonstrates, with a for loop, you're telling the computer how to loop. With forEach(), you're just declaring what you want to do for each element, and JavaScript handles the "how" for you.


The Anatomy of forEach() and the Callback Function

The forEach() method works by executing a function you provide for every element in the array. This function-passed-as-an-argument is a very important concept in JavaScript called a callback function.

Think of it like this: you're telling forEach(), "Here's a set of instructions (my callback function). Please run these instructions once for every item in my array."

The syntax looks like this:

array.forEach(callbackFunction);

The real power comes from what JavaScript passes to your callback function on each iteration. It automatically provides three arguments:

  1. element: The current element being processed in the array.
  2. index (optional): The index of the current element.
  3. array (optional): The array forEach() was called upon.

Let's see this in more detail.

Array methods

The article 'Array methods' from javascript.info offers a concise, text-based explanation of the forEach syntax and its parameters.

Read the section titled 'Iterate: forEach'. Focus on the syntax block and the example that shows how the item, index, and array are all available within the callback.

Here's a practical example using those parameters:

const fruits = ['apple', 'banana', 'cherry'];

fruits.forEach((fruit, index, arr) => {
  console.log(`At index ${index} of array [${arr}], we have a ${fruit}.`);
});

Running this code would produce:

At index 0 of array [apple,banana,cherry], we have a apple.
At index 1 of array [apple,banana,cherry], we have a banana.
At index 2 of array [apple,banana,cherry], we have a cherry.

Different Ways to Write the Callback

Since the callback is just a function, you can define it in several ways. This flexibility is key to writing clean and modern JavaScript. The video we started with explains these different syntaxes clearly.

Array forEach Method in JavaScript | JavaScript Array Methods | Beginners tutorial

Let's return to the Code Explained video. This next segment demonstrates the three primary ways to provide a callback function to forEach.

Watch from 03:40 to 06:19. The video will show you how to use: A named function (defined separately and passed by name). An inline function expression (defined directly inside forEach). An arrow function (the modern, concise ES6 syntax).

The arrow function syntax is the most common one you'll encounter in modern codebases, especially in Next.js and React, so it's the most important one to get comfortable with.

Test your understanding!

You have an array of user objects. Your task is to log a greeting for each user to the console.

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
];

Using the forEach method and an arrow function, write the code that will produce the following output in the console:

Hello, Alice!
Hello, Bob!
Hello, Charlie!
Show answer
const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
];

users.forEach(user => {
  console.log(`Hello, ${user.name}!`);
});

Explanation: forEach iterates over the users array. For each iteration, the current object is passed to the arrow function as the user parameter. We then access the name property of that object (user.name) and use a template literal to construct and log the greeting.


Under the Hood: forEach as Syntactic Sugar

You have a preference for understanding the "deep theory" of how things work. forEach() is a perfect example of what developers call syntactic sugar—it's a simpler, cleaner syntax for something that could be done in a more verbose way (in this case, with a for loop).

Let's pull back the curtain and see what forEach is actually doing.

How Array.forEach() works under-the-hood in vanilla JS

This article, 'How Array.forEach() works under-the-hood' by Chris Ferdinandi, gives a brilliant explanation of forEach as syntactic sugar and even shows you how it could be built from scratch.

Read the sections 'Looping arrays' and 'Array.forEach() is syntactic sugar on top of a for loop'. The code block at the end showing the implementation of forEach on the Array.prototype is the key takeaway here. It reveals that under the hood, it's just a for loop calling your callback function.

Understanding this isn't just academic. It helps explain some of the behaviors and limitations of forEach, which we'll cover next.


Key Characteristics and Limitations

forEach is excellent, but it's important to know its specific rules.

  1. It does not return a value. The forEach() method itself returns undefined. It is used purely to cause a "side effect" for each element—like logging to the console, saving to a database, or modifying an external variable. The function you pass to it can return something, but forEach will ignore it.

  2. You cannot stop or skip iterations with break or continue. This is a critical difference from a for loop. Because your code is running inside a callback function, a return statement will only exit the current function call, not the entire loop. Using break will cause a syntax error.

This video segment explains this limitation very clearly.

Array forEach Method in JavaScript | JavaScript Array Methods | Beginners tutorial

This final clip from the Code Explained video demonstrates why you can't use break inside a forEach loop and why it results in an error.

Watch from 06:07 to 07:39. The video directly contrasts a for loop where break works with a forEach loop where it doesn't.

If you need to terminate a loop early, a for...of loop (which we saw in Module 5) is often the best choice.


Conclusion

In this lesson, you've learned how to use the forEach() method to create clean, readable loops. This is a massive step up from managing manual for loops and is a cornerstone of modern JavaScript data manipulation.

Key Takeaways:

  • forEach() is a method on arrays that executes a callback function once for each element.
  • The callback function automatically receives the element, its index, and the original array as arguments.
  • The preferred modern syntax for the callback is an arrow function.
  • forEach() is "syntactic sugar" over a for loop; it handles the iteration mechanics for you.
  • forEach() always returns undefined and is used for its side effects.
  • You cannot use break or continue to stop or skip a forEach loop. The loop will always run to completion for every element.

Next Up

forEach() is fantastic for doing something for each element. But what if you want to create a new array based on the original? For example, what if you have an array of numbers and you want a new array where each number is doubled?

In our next lesson, we will explore the map() method. While it looks very similar to forEach(), its purpose is fundamentally different: map() is designed to transform an array into a new one.