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:
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: