Skip to content
Related Articles

Related Articles

Improve Article
Difference between forEach and for loop in Javascript
  • Last Updated : 04 Mar, 2021

This article describes the difference between a forEach and for loop in detail. The basic differences between the two are given below.

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:

Javascript




<script>
for (let i = 1; i <= 5; i++)
{
    document.write(i + "<br/>");
}
</script>

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 1: This example shows the forEach method with a callback function.

the 

Output:

1
2
3
4
5

Example 2: 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
For LoopforEach 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.
My Personal Notes arrow_drop_up
Recommended Articles
Page :