RxJS icon Launch Deal: Get $100 off the RxJS Kickstart Bundle now!

RxJS Masterclass is here. 2-course bundle - buy now (discount applied at checkout).

days
hours
mins
secs

Exploring Array ForEach in JavaScript

Mar 24, 2020 6 mins read

JavaScript post
JavaScript icon

Want to level up your JavaScript skills? Who doesn't. Here's what you need to know

Show Me View JavaScript courses

Welcome to the first article in this exploring array prototypes series where you will learn how to use the array prototype method - ForEach! In this article, you’ll learn how, when and why you should use ForEach that covers a lot of real-world tips and common pitfalls developers new to ForEach typically have.

Follow the Array Prototype Series!

You can also follow along with the rest of this series of posts on Array prototype methods:

Not only will you uncover all common practices and syntax you need to use on a daily basis, I’ve also included a lot of hints and tips from over the years writing JavaScript.

Now it’s time to dive into array ForEach!

What is ForEach?

ForEach is a method that exists on the Array.prototype. It provides a way for us to loop over an array of elements - and perform an action inside a callback function.

Here’s what the syntax is for the ForEach method in JavaScript:

array.forEach(callback[, thisArg])

ForEach was introduced in ES5 as a new helper method. I’d encourage you to also read the Array.prototype.forEach specification.

The first argument is a callback function, which is given three arguments, currentValue, the index and the current array. The callback function is invoked on every item in the array, passing us the item in the array as well as it’s index.

The second is the (optional) this context, should you wish to pass a new object as a reference to change the execution context.

ForEach has no return value unlike some other array prototype methods we’ll explore in this series.

Using ForEach in JavaScript

In this next section, we’ll explore when to use ForEach and look at some array ForEach examples in JavaScript. I’ve also thrown in an example of using for...in without Array.prototype.forEach so you can compare the “old” way of doing things!

When To Use ForEach

The time to reach for ForEach is when you need to iterate over an array without needing a return value - it’s callback expects no return value, and the finished execution of ForEach returns nothing. Treat it like a one-way street. This is not the case in other array prototype methods like it’s sibling Array Map.

Generally, ForEach is the basic entry level loop tool, and after learning it here you can progress onto the more dynamic methods that arrays give us.

As ForEach accepts a callback function, it’s important to note that this will create new function scope. A traditional looping approach via a for...in will not create new function scope on each iteration.

My recommendation would be to start using ForEach and revert to a different for loop style if you need finer-grained control of your loop - such as breaking a loop, looping backwards and more - all of which a ForEach cannot do.

ForEach Basic Example

Let’s look at how we can loop over array elements using ForEach. Here’s our data structure, a nice array with some objects inside:

const items = [
  { id: '🍔', name: 'Super Burger', price: 399 },
  { id: '🍟', name: 'Jumbo Fries', price: 199 },
  { id: '🥤', name: 'Big Slurp', price: 299 }
];

A most basic loop would allow us to print out each object in our array, as well as its index position:

items.forEach(function(item, index) {
  console.log(item, index);
});

We would then see something like this being printed out in the console (note the index number at the end too):

{ id: '🍔', name: 'Super Burger', price: 399 }  -  0
{ id: '🍟', name: 'Big Fries', price: 199 }  -  1
{ id: '🥤', name: 'Big Slurp', price: 299 }  -  2

Check it out:

So, you now know how to obtain each array element, and its index. This opens up many opportunities.

ForEach Real-World Example

Let’s move to a more ‘real-world’ scenario where you may be solving a particular problem.

Assume we want to display the names of an order to show the user, we could construct a new <li> element for each array element, and inject it into the DOM (bonus points for using an arrow function):

const app = document.querySelector('#app');

items.forEach((item) => {
  app.innerHTML += `
    <li>
      ${item.id} ${item.name} - ${(item.price / 100).toFixed(2)}
    </li>`;
});

Remember though: Arrow functions have no this context and therefore if you supply a thisArg as mentioned earlier - it won’t work. As it’s not very common to do this, we shouldn’t need to worry. Choose wisely!

Check the live output to see how ForEach behaves:

Bonus: For Eaching without ForEach

Using a for...in approach, here’s traditionally what one would have to write to achieve a For Each without ForEach as a method. Here’s a side-by-side comparison of the newer array ForEach approach versus the traditional imperative For Each:

const app = document.querySelector('#app');

// Declarative approach: Array.prototype.forEach
items.forEach((item) => {
  app.innerHTML += `
    <li>
      ${item.id} ${item.name} - ${(item.price / 100).toFixed(2)}
    </li>`;
});

// Imperative approach: For...in Each
for (let i = 0 ; i < items.length; i++) {
  const item = items[i];
  app.innerHTML += `
    <li>
      ${item.id} ${item.name} - ${(item.price / 100).toFixed(2)}
    </li>`;
}

Both achieve the identical output, it’s merely how we compose the code.

Whilst technically the ForEach method on JavaScript arrays is more “functional” style, it does not return anything - therefore cannot be chained as part of a series of operators that transform data, for example .map().filter() which we’ll learn about shortly.

ForEach is a nice and clean API and should be thought about as a one-way street. Here, I’m simply using it to render, there is no further action taking place and I get no return value from the method call.

Using ForEach or the newer for...of is preferred for simple looping.

Summary

ForEach is a great place to get started with JavaScript loops. Moving from a traditional for...in loop, the ForEach method can be introduced to bring a more functional approach and style to your programming.

If you’re enjoying this series, please keep following! To learn more JavaScript practices at this level and comprehensively, I’ve put together some online videos that explore the entire JavaScript language and the DOM - I’d encourage you to check them out if you are serious about JavaScript.

You’ve now learned how to use a ForEach to loop over an array in JavaScript! Here’s a brief recap of what we’ve talked about and some extra details:

  • ForEach is great for simple looping as it doesn’t return any values
  • You can access the array you’re looping in the third argument of the callback
  • You can change the this context via a second argument to .forEach(callback, thisArg) so that any references to this inside your callback point to your object
  • You can use arrow functions with ForEach but remember that this will be incorrect if you also supply a thisArg due to arrow functions not having a this context
  • You cannot ForEach in reverse or break a ForEach, use for...in or for...of
  • Using ForEach will skip empty array slots
  • You shouldn’t need to in this day and age of evergreen browsers, but use a polyfill for older browsers if necessary

Thanks for reading, happy looping!

Go to the next article in this series - Exploring Array Map!

Love the post? Share it!

Lots of time and effort go into creating all our blogs, resources and demos, we'd love if you'd spare a moment to share this one!