Question

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;
});
Was it helpful?

Solution

.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.

OTHER TIPS

Check out jQuery map vs. each and https://learn.jquery.com/using-jquery-core/iterating/

In summary, it depends on what you want to do. $.each() uses the same array whereas $.map() returns a new one. The order of the passing argument is reversed in $.map() to match that of the native .map() method available in ECMAScript 5. It's not all about how you iterate through the arrays/object, but if and how the original array/object is modified. A plus is that with $.each() you can use the keyword this within the function to reference the current element of the array/object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top