DEV Community

Discussion on: Javascript Shorthand Coding Techniques

Collapse
 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan

I'm not sure I understand. A regular for loop doesn't return anything either. This is equivalent to the examples he gave, but it's more legible and compact.

Thread Thread
 
eth2234 profile image
Ebrahim Hasan

Both forEach and for of can be used, forEach is used in arrays while for of can be used in arrays,maps,set or any iterable member objects.

Thread Thread
 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan

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.

Thread Thread
 
eth2234 profile image
Ebrahim Hasan • Edited

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]));