javascript

forEach in Javascript : 3 helpful things to learn

In this article, I have explained forEach in javascript. This loop works only with Arrays, Maps and Sets. 

Table of Contents
Syntax
Parameters
Description of forEach in Javascript
Performance

First, an example for those who came here to take a glance at the syntax quickly.

['apple', 'banana', 'orange'].forEach((fruit) => {
console.log(fruit);
});

//apple
//banana
//orange


Syntax

array.forEach(function(currentElement, index, arrayInstance), thisValue)

Parameters

currentElement: Current array element.
index: Current iteration index.
arrayInstance: An instance of the actual array.
thisValue: Default value of ‘this’ in function scope.

Description of forEach in javascript

Javascript forEach() loop works with Arrays, Maps or Sets. An iteration always starts from index zero and moves towards a higher index.

This loop accepts two parameters, a mandatory callback function and an optional ‘this’ value reference.

The callback function accepts 3 parameters. The first one is currentElement ( from the above example). It represents the current array element at any point of the iteration and this is a mandatory parameter.

Example of currentElement parameter:

['apple', 'banana', 'orange'].forEach((fruit) => {
console.log(fruit);
});

//apple
//banana
//orange

The second parameter of the callback function is index (from the above example). It is an optional parameter which contains the index value of the current element.

Example of index parameter:

['apple', 'banana', 'orange'].forEach((fruit, index) => {
console.log(index);
});

//0
//1
//2

The third parameter arrayInstance (from the above example) is another optional parameter. It contains an instance of the set /map /array object, on which the forEach() loop is running.

Example of arrayInstance parameter:

['apple', 'banana', 'orange'].forEach((fruit, index, arr) => {
console.log(arr);
});

//["apple", "banana", "orange"]

forEach() loop takes a second optional parameter thisValue (from the above example). It provides an option to set a default value of ‘this’ object inside the callback function.

Example of thisValue with callback function:

var obj = {a:1, b:2, c:3};
Object.keys(obj).forEach(function(item){
console.log(this[item]);
}, obj);

//1
//2
//3

An exception that occurs in case if the callback is an arrow function. The reason being, the arrow function body contains lexical ‘this’ reference. Which is ‘this’ reference from the closure that contains the forEach() function. Hence, no other outer parameter can override the value of ‘this’ inside an arrow function. See the below example.

Example of thisValue with arrow function:

var obj = {a:1, b:2, c:3};
Object.keys(obj).forEach((item)=>{
console.log(this[item]);
}, obj);

//undefined


Performance

In conclusion, forEach in Javascript is a very convenient feature. While speaking of performance, this loop is much slower than the usual for loop in javascript. Below are the steps that each loop performs in the background.

For loop

  1. The index variable is set to an initial value that is provided during declaration.
  2. On every iteration, checks whether or not to exit the loop
  3. Runs the code written inside the loop body.
  4. After every iteration increases the index value.
  5. Back to step 2

forEach() loop

  1. Declares the callback function
  2. On every iteration, checks if there is a next element to process.
  3. Calls the callback function for the next element. A new execution context is created for each iteration.
  4. Run the callback function body.
  5. Return to step 2

The modern browsers optimize forEach() function calls and in certain cases, this function runs even faster.

One drawback of forEach() loop is that, there is no way to stop or break a forEach() loop. Hence, the below code is useless:

arrayOfItems.forEach(function() {
  // do something
  return false
});

For these kind of requirements, we can use .map() function.

Use forEach loop with JS objects

At the beginning of this article, I have mentioned that the forEach in javascript works only with Arrays, Maps and Sets. And the good news is, there is a workaround to make forEach work with an object as well. Modifying this code will work with nested objects.

If you have read the thisValue parameter section above, then you already know it.

var obj = {a:1, b:2, c:3};
Object.keys(obj).forEach(function(item){ 
console.log(this[item]);
}, obj); //1
//2
//3