For a little while now javascript has the "map" function to loop over arrays.
It appears possible to use it as a 'foreach' operator for example:
fruitbowl.map(function(fruit){
... do stuff with fruit
})
Is this better or worse than saying
for(var i in fruitbowl){
... do stuff with fruitbowl[i]
}
Saves having to use the index but adds a callback; it doesn't seem very common so I hesitate to use it but still want to.
The three methods you mention have different purposes.
The purpose of the Array.prototype.map
method is to create a new array with the results of calling the callback function on every array element.
The purpose of the Array.prototype.forEach
method is to iterate over an array, executing the provided callback function once per array element.
The purpose of the for...in
statement is to enumerate object properties.
I think that the for...in
statement should be avoided to traverse any array-like1 object, where the real purpose is iterate over numeric indexes and not enumerate the object properties (even knowing that those indexes are properties).
Reasons to avoid for...in
to iterate array-like objects:
Array.prototype
object, you will see all those extended properties.Give a look to this article:
1 By array-like objects I mean any object that contains sequential numeric properties, and a length
property
That use is considered valid, but it's bad style to use a map operation strictly for its side effects instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With