I’m using UnderscoreJs. Consider this code:
var docs = [
{name : 'Anders', niche : 'Web Development'},
{name : 'Johnny', niche : 'Design'},
{name : 'Eric', niche : 'PhotoShop'}
];
var newDocs = _.map(docs, function (doc){
delete doc.niche;
return doc;
});
It doesn’t matter if I use .each
or .map
here. The outcome is exactly the same.
What is really the difference between the two in the case above?
4
Answers
_.each(list, iteratee)
_.map(list, iteratee)
see documentation
map
is intended to be a functional mapping method: its function argument should return a value, but is not expected to have any side-effects.each
is just a functional replacement for an imperativefor
loop: its purpose is to have an effect, and it is not expected to return any value.For example, this would be a more appropriate use for
map
:Whereas this would be an appropriate use for
each
:Your assertion that the results are “exactly the same” is untrue. The
_.each()
function returns the original list, but_.map()
returns a new list. You’re directly modifying the original objects as you go, so you end up with references to the same objects in each list, but with_.map()
you end up with two separate array instances.You can just look at the source code to see the difference:
_.each
:_.map
: