HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

6) Advanced Arrays, Strings and Functions Lesson

JavaScript .forEach() for Array Iteration

11 min to complete · By Ian Currie

Now that you covered what arrow functions are and how to write them in the previous lessons, now it's time to get to know a really useful array method. It's a higher order function called .forEach() and it'll be your gateway into other similar array methods like .map() and .filter(). These methods are designed for expressive iteration over the elements in an array.

The .forEach() Method

The .forEach() method is an array method that takes a callback function as an argument. It iterates through the elements in the array and executes the callback function on each element. The callback function can be defined as a function expression, an arrow function or a reference to a function. The syntax for .forEach() with an arrow function is as follows:

array.forEach((element) => {
  // do something with element
});

The callback function can take up to three arguments, but the first one is the only one that is required. The other arguments will be covered in later sections in this lesson.

Iterating Over an Array with .forEach()

Say you have an array of numbers and you want to print each number to the console. You could do this with a for loop like this:

let numbers = [1, 2, 3, 4, 5];

for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}
/*
OUTPUT
1
2
3
4
5
*/

Or you could do it with the .forEach() method like this:

let numbers = [1, 2, 3, 4, 5];

numbers.forEach((number) => console.log(number));
/*
OUTPUT
1
2
3
4
5
*/

As another example, imagine you had a list of temperatures that you wanted to convert and log to the console:

let tempsInC = [12, 14, 16, 30, 21, 35, 0, -10];

function cToF(tempInC) {
  return tempInC * 1.8 + 32;
}

tempsInC.forEach((tempToConvert) => {
  let newTemp = cToF(tempToConvert);
  console.log(`${tempToConvert}C is ${newTemp}F`);
});

/*
OUTPUT
12C is 53.6F
14C is 57.2F
16C is 60.8F
30C is 86F
21C is 69.80000000000001F
35C is 95F
0C is 32F
-10C is 14F

As you can see, the .forEach() method is a more concise way to iterate over an array than a for loop.

Once you're used to seeing this type of method in action, it becomes more readable than a for loop. It's also a less code to write, which is always a good thing! Mainly because it reduces the chances of making a mistake! You no longer have to declare a variable, create a condition to finish the loop, and increment the variable. You just have to write the callback function and the method takes care of the rest.

Arguments of the .forEach() Callback Function

The callback function that you pass to the .forEach() method can take up to three arguments. The first argument is the current element in the array. The second argument is the index of the current element. The third argument is the array itself:

array.forEach((element, index, array) => {
  // do something with element, index, and array
});

The arguments are as follows:

  • element: The current element in the array
  • index: The index of the current element
  • array: The array itself

Take a look at an example of how you can use these arguments in the callback function:

let numbers = [1, 2, 3, 4, 5];

numbers.forEach((number, index, array) => {
  console.log(`The number at index ${index} is ${number}`);
  console.log(`The array is ${array}`);
});

/*
OUTPUT
The number at index 0 is 1
The array is 1,2,3,4,5
The number at index 1 is 2
The array is 1,2,3,4,5
The number at index 2 is 3
The array is 1,2,3,4,5
The number at index 3 is 4
The array is 1,2,3,4,5
The number at index 4 is 5
The array is 1,2,3,4,5
*/

The index argument can be very useful, especially if you need to access the element that comes before or after the current element. The array argument can be useful if you need to access the array itself inside the callback function, but that is less common to need than the index argument.

The .forEach() method itself can accept a second argument, which is optional. This argument allows you to bind an object to the this keyword within the callback function.

Returning Values from the .forEach() Method

The .forEach() method does not return anything. It simply iterates over the array and executes the callback function on each element. If you need to return a new array, you can use other array methods like the .map() method.

It's also worth noting that returning something in the callback also has no effect.

Breaking Out of a .forEach() Loop

The .forEach() method does not have a way to break out of the loop. That is, the break keyword has no effect. If you need to break out of a loop, you should use a for loop instead.

Likewise, the continue keyword has no effect. If you want to skip an iteration, you can use the return keyword, which will prevent the rest of the code in the callback function from executing. Even though the return value has no effect on the rest of the .forEach() method, it will still prevent the rest of the code in the callback function from executing.

The .forEach() Method is For Side Effects

The .forEach() method is for side effects and does not change the array. Trying to change the array while iterating over it with .forEach() will lead to unexpected results. If you need to change, or mutate the array, you should use other techniques, like the .map() array method:

let numbers = [1, 2, 3, 4, 5];

numbers.map((number) => number * 2); // [2, 4, 6, 8, 10]

Summary:

You’ve expanded your JavaScript knowledge by learning about the .forEach() method, a tool that makes array iteration simple and straightforward. Here's what you've gathered:

  • Discovered that .forEach() is an array iteration method that uses a callback function to execute code for each item in an array.
  • Grasped the use of arrow functions as a concise way to define the callback passed to .forEach().
  • Comprehended that .forEach() is often more readable and requires less boilerplate code than a traditional for loop.
  • Learned that the callback function for .forEach() can accept up to three arguments: the current element, the current index, and the array itself.
  • Acknowledged the limitations of .forEach(), such as not being able to break out of the loop with break and that the method doesn’t return any value.
  • Understood that while .forEach() is used to execute side effects rather than mutate an array, methods like .map() are better suited for creating new arrays based on existing ones.