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

Posted by John Mee on Stack Overflow See other posts from Stack Overflow or by John Mee
Published on 2010-04-23T04:54:50Z Indexed on 2010/04/23 5:03 UTC
Read the original article Hit count: 225

Filed under:
|

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:

var arr = ['a','b','c']
var doubles = arr.map(function(val){ 
                  return val + val 
              })

Is this better or worse than saying

for(var i in arr){ ...

50/50: 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.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about loop