In jQuery, the map and each functions seem to do the same thing. Are there any practical differences between the two? When would you choose to use one instead of the other?
In jQuery, the map and each functions seem to do the same thing. Are
Share
The
eachmethod is meant to be an immutable iterator, where as themapmethod can be used as an iterator, but is really meant to manipulate the supplied array and return a new array.Another important thing to note is that the
eachfunction returns the original array while themapfunction returns a new array. If you overuse the return value of the map function you can potentially waste a lot of memory.For example:
You can also use the map function to remove an item from an array. For example:
You’ll also note that the
thisis not mapped in themapfunction. You will have to supply the first parameter in the callback (eg we usediabove). Ironically, the callback arguments used in the each method are the reverse of the callback arguments in the map function so be careful.