Register Login

forEach() Loop in JavaScript Array

Updated Jul 07, 2022

The fundamental purpose of loops is to execute (or iterate) the same code a number of times. The iteration is limited to a specific number of a particular condition.

There are different loops, like for loop, do-while loop, and the while loop, but modern JavaScript supports a new kind of loop, forEach loop. This article presents the JavaScript forEach() method thoroughly with suitable examples.

What is forEach loop?

The forEach() method invokes a different function for each entry in an array. The forEach() method iterates through an array's items while calling a function. For empty items, the forEach() function is not used. Programmers can use Maps and Sets using the forEach() function.

The forEach method has the following syntax:

array.forEach(function(element, index, arr), thisArg)

The forEach() method has two parameters. These are described below.

  1. Function(): It is a callback function that executes for each element in an array. It is a required parameter, and it has three arguments.
    1. Element- It is the value of the current item. It is a required parameter.
    2. Index- It is the index of the current element. It is an optional parameter.
    3. Arr- It is the array of the current element. It is an optional parameter.
    4. thisArg- It is an optional parameter, and by default, it is undefined. It contains the context that passes to the callback function as this.

Return Value: The return value of forEach() is undefined. 

Printing the Contents of an Array:

Example:

let name = ["Alex", "Bob", "Casey"];
name.forEach(function f(element){
  console.log("Hello " + element + ", welcome to the JavaScript forEach method." )
});

Output:

Run Code

The programmer has defined an array of names, uses the forEach() to iterate each element in the initialized array, and prints the result in the console.

Updating or Adding Elements in an array list:

Example:

let EmployeeName = ['Alice', 'Boby', 'Henry'];
EmployeeName.forEach(function (element, index, arr) {
    arr[index] = element + " Halam";
})
console.log(EmployeeName);

Output:

Run Code

The programmer has created an EmployeeName array, and in the forEach, he has passed three parameters, the value of the current item, the index of the current element, and the array object. And added the string Halam to the array element using the array object and index value.

The Arrow Function and the forEach():

Programmers can use the arrow function with the forEach() to write a program.

Example:

let name = ["Alex", "Bob", "Casey"];
name.forEach(element => {
  console.log("Hello " + element + ", welcome to the JavaScript forEach method." )
});

Output:

Run Code

Using thisArg:

Example:

const EmployeeDetail = {
  name: 'Alex Hales',
  age: '26',
  designation: 'Backend Developer'
};
console.log("The details of the employee are as follows");
 
Object.keys(EmployeeDetail ).forEach(function( element ) { 
  console.log( this[ element ] );
 
}, EmployeeDetail ); 

 Output:

Run Code

The programmer has given thisArg parameter. It will contain the context and passes to the callback function.

There is another way of writing the above program using bind, but it is a bit slow.

Example:

const EmployeeDetail = {
  name: 'Alex Hales',
  age: '26',
  designation: 'Backend Developer'
};
console.log("The details of the employee are as follows");
 
Object.keys(EmployeeDetail ).forEach(function (element ) { 
  console.log( this[ element ] );
 
}. bind(EmployeeDetail )); 

Output:

Run Code

forEach() with Set:

Set contains only unique values.

Example:

const name = new Set (['Alice', 'Boby', 'Henry']);
name.forEach(function f(element){
  console.log("Hello " + element + ", welcome to the Example of forEach method using Set." )
});

Output:

Run Code

The programmer has defined a set using a new keyword. The forEach() iterate the set and prints the output. 

Now consider a situation where the programmer has defined duplicate values in Set. If the programmer iterates the Set using forEach() and prints the result, then the output value will be all unique.

Example:

const name = new Set (['Alice','Boby','Boby','Henry','Alice']);
name.forEach(function f(element){
  console.log("Hello " + element + ", welcome to the Example of forEach method using Set." )
});

Output:

Run Code

forEach with Map:

A Map can hold any datatype of key-value pairs.

Example:

let map = new Map([
  ["Tomato", "5.5 kg"],
  ["Potato", "9 kg"],
  ["Onion", "6 kg"]
]);
map.forEach (function (value,element){
    console.log(element + '- ' + value);
});

Output:

Run Code

The programmer has created a map using the new map procedure. Using the forEach(), the programmer iterates the Map and prints the result.

Break the Loop:

In the forEach(), the break statement is not allowed. If the programmer wants to use the break inside the forEach(), it will display a SyntaxError: Illegal break statement.

Example:

let map = new Map([
  ["Tomato", "5.5 kg"],
  ["Potato", "9 kg"],
  ["Onion", "6 kg"]
]);
 
map.forEach (function (value,element){
    console.log(element + '- ' + value);
    break;
});

Output:

Run Code

Conclusion:

This article provides the complete work and utilization of forEach with examples. The forEach is very similar to other loops, but the feature like the break does not work in forEach(). Apart from that, the forEach() makes it easy for the programmers to iterate statements effortlessly. Object iterations also becomes easy and seamless.


×