jQuery .each() vs. .map() without return

neridaj picture neridaj · Mar 19, 2014 · Viewed 12.7k times · Source

Is there any difference between .each() and .map() when no value is returned? Is there any benefit in using one or the other in this case?

myList.map(function(myModel, myIndex){              
    myModel.itemOne = itemOne;
    myModel.itemTwo = itemTwo;
    myModel.itemThree = itemThree;
});

myList.each(function(myModel, myIndex){             
    myModel.itemOne = itemOne;
    myModel.itemTwo = itemTwo;
    myModel.itemThree = itemThree;
});

Answer

jfriend00 picture jfriend00 · Mar 19, 2014

.map() is designed to both iterate and create a new resulting array.

.each() is designed to be an iterator (no new array created).

Either will work for plain iteration, though I would argue that the intent of your code is clearer if you are just doing an iteration if you use .each() since that is its intended and only purpose.

As for functionality differences besides the creation of the array, jQuery's .each() allows you to terminate the iteration by returning false from the callback. jQuery's .map() does not have a way to terminate the iteration.