forEach can also be used with arrays, maps, and sets. To my knowledge, the only advantage that a traditional for loop has is the ability to traverse objects.
Ebrahim Hasan is a full stack web developer, currently working as a freelancer on freelancer.com, he is a co-owner of a swedish and an Egyptian company.
But note that this is not a traditional for loop, this is a "for of", it even can loop through Strings (instead of converting a string to an array or using a for with the length)
I think the only advantage that I see to use the for loop is having one common way to loop through elements, or if you have a function that can have different iterable object types, example:
forEach
can also be used with arrays, maps, and sets. To my knowledge, the only advantage that a traditionalfor
loop has is the ability to traverse objects.But note that this is not a traditional for loop, this is a "for of", it even can loop through Strings (instead of converting a string to an array or using a for with the length)
I think the only advantage that I see to use the for loop is having one common way to loop through elements, or if you have a function that can have different iterable object types, example:
const loopThrough = (object) => {
for(const n of object) {
console.log(n);
}
};
loopThrough("hello");
loopThrough(["h","e","l","l","o"]);
loopThrough(new Set([1, 2, 3, 4, 5]));