Difference between forEach and for loop in Javascript
In JavaScript, both forEach and for loops are used to iterate over arrays or collections, but they differ in usage and behavior. forEach is a higher-order function that simplifies iteration with built-in array methods, while for loops offer more control, flexibility, and broader application.
For Loop
The for loop is one of the original ways to iterate through arrays or collections in JavaScript. It allows you to specify the initialization, condition, and increment all in one line, making it ideal when the iteration count is known.
Syntax
for (initialization; condition; increment)
{
// code to be executed
}
Example: In this example, this loop iterates from 1 to 5. For each iteration, it logs the current value of i to the console.
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.
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. |
Conclusion
The for loop is better suited when performance, control over iterations, or early exit conditions are important. The forEach loop, on the other hand, is ideal for clean, readable code when looping through arrays without needing complex logic. Choosing between the two depends on the specific requirements of your code.