JavaScript forEach (Arrays) - Simplified

There are various approaches to loop through every element in an array, such as the for() loop statement. JavaScript forEach() is one of the best ways which is used to perform a certain predefined function on each and every element of the array.

Now in this article, let's understand firmly what forEach() is about with some straightforward and clean examples. If you are studying Web Development you will come across arrays pretty early on. Once you come to that point, you will need to learn and understand the JavaScript forEach loop.

JavaScript forEach

πŸ”₯ Learn JavaScript - Beginner Friendly!

πŸ‘‰Β JavaScript Array Filter – Made Easy
πŸ‘‰Β JavaScript Array Find – Made Easy
πŸ‘‰Β Difference between Let and Const
πŸ‘‰Β Sorting Numbers in JS!
πŸ‘‰Β Store User Input in a variable with JS!
πŸ‘‰Β JavaScript Spread Operator – Made Easy
πŸ‘‰Β JavaScript Slice (Arrays) – Made Easy
πŸ‘‰Β JavaScript Slice(Strings) – Made Easy
πŸ‘‰Β JavaScript Includes – Made Easy
πŸ‘‰ JavaScript forEach (Arrays) - Made Easy
πŸ‘‰ toLocaleDateString in JavaScript - For Humans
πŸ‘‰ JavaScript Fetch API - Made Easy

Table of Contents

What Is Javascript forEach()?

The for() loop is a classic method of looping that iterates across an array for a predefined number of times.

However, in the case of forEach(), the loop statement iterates and passes a callback function to every element of the given array.

For a more precise understanding, let's look at the syntax below:

Syntax:

array.forEach(function(currentValue, index, arr), thisValue)
Code language: JavaScript (javascript)

Here,

  • function() - refers to the callback function that will be performed on each and every element of the array.
  • currentValue - refers to the value of the current array element.
  • index - refers to the index value of the current element.
  • arr - refers to the array of the current elements.
  • thisValue - refers to the value passed to the function.

Return Value

The return value of forEach() method is always undefined.

Why do you need the forEach Loop in JavaScript?

There are two ways to loop through an array. You can loop through an array with a simple for loop:

const testArray = ["Item 1", "Item 2", "Item 3"] for(let i = 0; i < todos.length; i++) { console.log(todos[i]) }
Code language: JavaScript (javascript)

Output:

Item 1 Item 2 Item 3
Code language: Bash (bash)

This is quite a bit of code that we can shorten using a forEach loop:

const testArray = ["Item 1", "Item 2", "Item 3"]; testArray.forEach(function(item) { console.log(item); });
Code language: JavaScript (javascript)

Which will return the same as above.

As you can see, the code for the forEach loop is much easier to read than the code for the for loop. But let's break it down.

The forEach Loop in JavaScript explained

through an Array and return certain values. forEach can only be used on Arrays, Sets, and Maps. The forEach loop takes a so-called Callback Function, in our case this function is called item. This Callback function runs once for every element in the array in ascending order. But you can call this Callback function whatever you want, let me demonstrate it.

const testArray = ["Item 1", "Item 2", "Item 3"]; testArray.forEach(function(hotDog) { console.log(hotDog); });
Code language: JavaScript (javascript)

We changed the item Callback function to hotDog, the output stays the same:

Item 1 Item 2 Item 3
Code language: Bash (bash)

Parameters of JavaScript forEach()

JavaScript forEach

1. Callback

The callback function and currentValue parameters are the required parameters of the forEach() statement. The callback is the function that performs the required action on each array element during the iteration.

A callback function called myFunction is used in this example to show how the forEach() method iterates over elements in an array and runs a specified function on each one.

let colleagues = ['Rita', 'Sarah', 'Adam']; // using forEach colleagues.forEach(myFunction); function myFunction(item) { console.log(item); }
Code language: JavaScript (javascript)

Output:

Rita Sarah Adam
Code language: Bash (bash)

2. thisArg

The thisArg or thisValue is a value to use as β€˜this’ when executing the callback.

Here, the thisArg parameter passes the β€˜this’ value whenever the callback function is invoked.

function Counter() { this.sum = 0 this.count = 0 } Counter.prototype.add = function(array) { array.forEach(function countEntry(entry) { this.sum += entry; ++this.count; }, this); }; const obj = new Counter(); obj.add([8, 7, 12]); console.log(obj.count); console.log(obj.sum);
Code language: JavaScript (javascript)

Output

3 27
Code language: Bash (bash)

3. Index

The index parameter refers to the index value of the elements present in the given array.

The following example uses the index argument to print both the index numbers and the values of the respective positions.

const students = ['Tia', 'Mary', 'Isabel', 'Jack', 'Abel']; students.forEach((number, index) => { console.log('Index: ' + index + ' Value: ' + number); });
Code language: JavaScript (javascript)

Output

Index: 0 Value: Tia Index: 1 Value: Mary Index: 2 Value: Isabel Index: 3 Value: Jack Index: 4 Value: Abel
Code language: Bash (bash)

4. Arr

The arr or array parameter refers to the current array on which the forEach() method will be performed on.

In the following example, we will be printing the whole array as the number of elements present in the array.

const students = ['Tia', 'Mary', 'Isabel', 'Jack', 'Abel']; students.forEach((number, index, array) => { console.log(array); });
Code language: JavaScript (javascript)

Output

[ 'Tia', 'Mary', 'Isabel', 'Jack', 'Abel' ] [ 'Tia', 'Mary', 'Isabel', 'Jack', 'Abel' ] [ 'Tia', 'Mary', 'Isabel', 'Jack', 'Abel' ] [ 'Tia', 'Mary', 'Isabel', 'Jack', 'Abel' ] [ 'Tia', 'Mary', 'Isabel', 'Jack', 'Abel' ]
Code language: JSON / JSON with Comments (json)

for() loop vs. forEach() loop

Though for() and forEach() are quite similar as they are used to execute a set of statements multiple times, their functionalities differ.

for() loop is:

  • One of the most prevalent iteration methods allows code to be executed several times.
  • Faster when it comes to executing statements.
  • Harder to read and write.
  • General-purpose loop.

forEach() loop is:

  • One of the newest loop statements that iterate the elements belonging to an array.
  • Quite slower in terms of traversing and executing statements.
  • Easier to read and write compared to for() loop.
  • Used only in arrays

More Examples using the forEach() Loop

1. Using forEach() Loop to Update Array Elements

We already know that the forEach() loop is used to iterate over an array and perform specific functions on them. With that concept in mind, we will be using it to update the content of the array in the following example.

let students = ['Amara', 'Lydia', 'Phil']; // using forEach students.forEach(myFunction); function myFunction(item, index, arr) { // adding strings to the array elements arr[index] = 'Hello ' + item; } console.log(students);
Code language: JavaScript (javascript)

Output

[ 'Hello Amara', 'Hello Lydia', 'Hello Phil' ]
Code language: Bash (bash)

2. Using forEach() Loop to Copy a Given Array

The forEach() loop is used to construct a new array from the elements of another array in this example. The twist is that we won't make an exact clone of the previous array; instead, we'll use forEach() to execute operations on the other array elements before pushing it to the new copy.

function func() { // Original array const items = [38, 27, 12]; const copy = []; items.forEach(function (item) { copy.push(item + item+2); }); console.log(copy); } func();
Code language: JavaScript (javascript)

Output

[ 78, 56, 26 ]
Code language: Bash (bash)

Conclusion

We've gone over detailed explanations of the JavaScript forEach() loop as well as multiple comprehensive coding examples in this article. With the knowledge learned today, try out the given examples to get a grip on this new concept.

There are, of course, many more things you can do with forEach, but this should cover the basics and give you a solid foundation on the JavaScript forEach method. I highly recommend checking out MDN and play around with the forEach loop in JavaScript to get a better understanding of it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.