Super Javascript
Home About RSS Guest Blogging 🐍 Snake

JavaScript forEach

JavaScript forEach

The JavaScript forEach function will run a function of your choice against every item of an array. It essentially does the same thing as a for loop, but it can make the coder shorter and easier to read in some situations.

Let’s walk through an example.

In the Javascript map tutorial we created a table of contents. We will use this example again, but instead of creating the table of contents as an array, we will write each line out to the console, which is a tool programmers use to see what their program is doing.

In this example we will start off with some chapter descriptions:

var descriptions = [
  'Introduction',
  'How to throw a ball',
  'How to catch a ball',
  'How to kick a ball'
];

And we want to print something like this to the console:

1. Introduction
2. How to throw a ball
3. How to catch a ball
4. How to kick a ball

However as a first step, we will write a program to print just the descriptions without the numbers to the console as this will be a good test of the JavaScript forEach function.

To write a single line to the console you might do something like this:

var text = 'Introduction';
console.log(text);

If you run this in a browser, and press F12 to view the console, you will see Introduction in the output window.

To do this for all the items, you can use forEach as follows:

var descriptions = [
  'Introduction',
  'How to throw a ball',
  'How to catch a ball',
  'How to kick a ball'
];

descriptions.forEach(function(description){
  console.log(description);
});

In the code above, there is a function that takes a description and prints that to the console:

function(description){
  console.log(description);
}

That function is passed into forEach so that it will be run on each of the items in the array, starting with ‘Introduction’.

Using Javascript forEach’s Index

The next step is to change the code to print out the numbers. We can take advantage of the index parameter passed back to us by forEach. This is set to 0 for the first item, and then 1,2.. etc. So we need to add 1 to this index to get the numbering 1,2,3.. etc.

Here is the code:

var descriptions = [
  'Introduction',
  'How to throw a ball',
  'How to catch a ball',
  'How to kick a ball'
];

descriptions.forEach(function(description, index){
  console.log((index + 1) + '. ' + description);
});

Let’s break down what is going on inside the log statement:

This give a console log output like the following:

1. Introduction
2. How to throw a ball
3. How to catch a ball
4. How to kick a ball

Pipelines

The forEach function is useful in pipelines, where you start with an array, and you do many things to all the items in an array.

For example you might have a bunch of values in miles, and you want to convert them to kilometers, and then print them to the console.

One way of doing this is by using map to do the conversion (more details in the Javascript map tutorial), and then using forEach to do the printing.

Here is how that is done:

var miles_array = [1.5, 6.0, 11.3];
var kilometers_per_mile = 1.60934;
var kilometers_array = miles_array
  .map(function(m) {
    return m * kilometers_per_mile;
  })
  .forEach(function(km) {
    console.log(km);
  })
  ;

The result is:

2.41401
9.65604
18.185542

This could have been done with just forEach and it would have been simpler. So why use map and forEach?

The reason is that in more complex JavaScript programs, the functions you pass into map and forEach might be complicated functions that you don’t want to rewrite again.

Imagine if instead of console logging you were converting to PDF. That would take a lot of code. And instead of converting from miles to kilometers, you were calculating taxes on an invoice. The chances are those functions would already be written and will be fairly complex. Being able to just pass them into map and forEach is particularly convenient.

This reuse of functions and pipelining is a principle called “composability”, and is important in programs to avoid reinventing the wheel each time you want to solve a problem.

Summary

This tutorial covers the basics of forEach which can be used as a shorthand for for loops and also to aid in building pipelines using more complicated functions.

Thanks for reading, and good luck.

Check out this great book:

See Also