DEV Community

Discussion on: How to iterate over an object in Javascript?

Collapse
 
rickdelpo1 profile image
Rick Delpo

The explanation as to why u cannot iterate over an object is because u need to transform the object into an array first then u can use the .forEach method on the array with either Object.keys(), Object.values(), or Object.entries().

Arrays imho are by far the most important data type !!

Collapse
 
peerreynders profile image
peerreynders

Arrays imho are by far the most important data type !!

I argue that the iteration protocols are far more generally applicable.

Array methods are limited to arrays, which means you always have to transform something to an array before you can do anything via array methods.

Unfortunately the current generation of IDEs makes it incredibly easy to discover methods-on-classes rather than functions-that-can-be-applied-to-a-type. That fosters an environment where methods are favoured, leading to array methods being trendy while for…of is being judged as "old school" even when it is entirely appropriate within JavaScript's scope.

One big advantage of the iteration protocol is that it can be implemented in a lazy fashion—when appropriate—which is simply not possible with array methods; with arrays you are forced to render the collection in full before you can start working on any item.

In the absence of iteration protocol support the .forEach() method is supported in a lot of surprising places (though I'm personally not a fan).