Open In App

Difference between forEach and for loop in Javascript

Last Updated : 26 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

For Loop

The JavaScript for loop is used to iterate through the array or the elements for a specified number of times. If a certain amount of iteration is known, it should be used.

Syntax:

for (initialization; condition; increment)  
{
// code to be executed
}

Example: In this example, we have used for loop.

Javascript




for (let i = 1; i <= 5; i++) {
    console.log(i);
}


Output

1
2
3
4
5

forEach loop

The forEach() method is also used to loop through arrays, but it uses a function differently than the classic “for loop”. It passes a callback function for each element of an array together with the below parameters:

  • Current Value (required): The value of the current array element
  • Index (optional): The index number of the current element
  • Array (optional): The array object the current element belongs to

We need a callback function to loop through an array by using the forEach method.

Syntax:

numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
// code to be executed
});

For every single element of the array, the function will be executed. The callback should have at least one parameter which represents the elements of an array.

Example: This example shows the use of the index parameter in the forEach method.

Javascript




numbers = [1, 2, 3, 4, 5];
 
numbers.forEach((number, index) => {
    console.log('Index: ' + index +
        ', Value: ' + number);
});


Output

Index: 0, Value: 1
Index: 1, Value: 2
Index: 2, Value: 3
Index: 3, Value: 4
Index: 4, Value: 5

Difference between For loop and for each loop

For Loop forEach Loop
It is one of the original ways of iterating over an array. It is a newer way with lesser code to iterate over an array.
It is faster in performance. It is slower than the traditional loop in performance.
The break statement can be used to come out from the loop. The break statement cannot be used because of the callback function.
The parameters are the iterator, counter, and incrementor. The parameters are the iterator, index of item, and array to iterate.
It works with the await keyword. The await keyword cannot be used due to the callback function. It may lead to incorrect output.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads