Difference between for loop and forEach in Javascript

    Aug 11, 2021       by Suraj Roy

To work with Arrays efficiently, One should be very clear about choosing a loop to have control over the iteration while loop.

In this article, We will see the major difference between for loop and forEach.

 

For Loop: This loop is used to iterate through the element of the array, Mostly used approach is getting used for a longer time.

Syntax:

for (initialization; condition; increment) {

  // block of code whih gets executed

}

 

Example:

const arr = [11, 20, 13, 24, 52];

for (let i = 1; i <= arr.length; i++){

      console.log('Element: ' + arr[i] + ', Index Value: ' + i);

}

 

Output

Index: 0, Value 11

Index: 1, Value 20

Index: 2, Value 13

Index: 3, Value 24

Index: 4, Value 52

 

forEach: This method is used to iterate the array items. It is the newer approach to looping through an array.It uses a function which a callback function for each element of an array having below properties:

  • Current Value: The current value of the Array, Its a required field.
  • Index: The index number of the current iteration of Array, It's a optional field.
  • Array: the object of array that current element belongs to


Syntax:

const arr = [11, 20, 13, 24, 52];

arr.forEach(function(element) {

  //block of code which will execute.

});

 

The callback function should have at least one parameter which represents the current value of the array. For each element of the array, the block of code will execute.

Example:

const arr = [11, 20, 13, 24, 52];

numbers.forEach((ele, index) => {

    console.log('Element: ' + ele + ', Index Value: ' + index);

});

 

Output

Index: 0, Value 11

Index: 1, Value 20

Index: 2, Value 13

Index: 3, Value 24

Index: 4, Value 52


 

Major Differences:

  1. For loop is approach which was used originally but the forEach is the newer approach for iterating the array element.
  2. Break statement can be used to break the for loop if required, But We cannot do anything like this with forEach.
  3. For loop works with await but forEach does not work perfectly with await.
  4. Performace with for loop is faster  than the forEach loop.

 


WHAT'S NEW

Find other similar Articles here: