When iterating over data, you can choose between a standard for loop or declarative array methods (like map, filter, reduce, or forEach).
When to use a For Loop:
- Control: When you need fine-grained control over initialization, conditions, or increments.
- Performance: Can be more efficient for very large datasets.
- Flow Control: When you need to use the
break statement to exit the loop early (array methods like forEach do not support break). - Mutation: When you want to mutate the original array in place.
When to use Array Methods:
- Readability: They provide a declarative syntax that is often easier to read.
- Immutability: Methods like
map, filter, and reduce return new arrays instead of mutating the original. - Composition: They can be chained together to perform complex transformations in a clean way.
// For Loop (Mutates original array)
let arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
arr[i] = arr[i] * 2;
console.log(arr[i]);
}
// Map Method (Returns new array, preserves immutability)
let arr = [1, 2, 3, 4, 5];
let doubled = arr.map(num => num * 2);
console.log(doubled);