views:

114

answers:

5

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.

+3  A: 

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

Ignacio Vazquez-Abrams
A: 

Readability is worth a lot. The map might be confusing to those who've never seen it used this way. It violates the "principle of least surprise."

Robert Harvey
+6  A: 

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:


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

CMS
+1  A: 

In Perl, map is used similarly but more naturally.

My rule of thumb is if it does not read better than a loop then don't use it. Difficult to debug. But for certain functions, map is more natural than a loop. If you need to scratch your head over it -- don't do it. Pity the guy who follows you, including yourself sometime from now!

drewk
A: 

Don't use map for its side effects. If your task is iterating over an array to do something with each object, use foreach. If you are mapping values, e.g. escaping an array of strings, use map. There's nothing like clarity and programmer intent over being clever.

Duncan