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.mapmethod is to create a new array with the results of calling the callback function on every array element.The purpose of the
Array.prototype.forEachmethod is to iterate over an array, executing the provided callback function once per array element.The purpose of the
for...instatement is to enumerate object properties.I think that the
for...instatement 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...into iterate array-like objects:Array.prototypeobject, 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
lengthproperty