Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use "map" as a substitute for "for each"/"for in"?

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.

like image 329
John Mee Avatar asked Dec 13 '22 22:12

John Mee


2 Answers

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:

  • Iterates over inherited user-defined properties in addition to the array elements, if you use a library like MooTools for example, which extend the Array.prototype object, you will see all those extended properties.
  • The order of iteration is arbitrary, the elements may not be visited in numeric order.

Give a look to this article:

  • Iteration VS Enumeration

1 By array-like objects I mean any object that contains sequential numeric properties, and a length property

like image 158
Christian C. Salvadó Avatar answered Jan 06 '23 08:01

Christian C. Salvadó


That use is considered valid, but it's bad style to use a map operation strictly for its side effects instead.

like image 26
Ignacio Vazquez-Abrams Avatar answered Jan 06 '23 10:01

Ignacio Vazquez-Abrams