These two functions, _.forEach
and $.each
, taken respectively from underscore
and jQuery
seems to make the same thing.
What are the possible reasons to prefer one implementation to the other?
each differs for the arguments passed to the callback. If you use _. forEach , the first argument passed to the callback is the value, not the key. So if you don't bother at all about the key you should use _.
Differences between forEach() and map() methods:The forEach() method does not create a new array based on the given array. The map() method creates an entirely new array. The forEach() method returns “undefined“. The map() method returns the newly created array according to the provided callback function.
The main difference between forEach and filter is that forEach just loop over the array and executes the callback but filter executes the callback and check its return value.
_.forEach
and $.each
differs for the arguments passed to the callback.
If you use _.forEach
, the first argument passed to the callback is the value, not the key.
So if you don't bother at all about the key you should use _.forEach
.
Other differences:
_.forEach
it will be a bit faster as it uses the native Arrray.prototype.forEach
in modern browsers.Both of them mainly provide a replacement for the forEach function that isn't available in IE8.
They don't add much if you're iterating over arrays.
The main difference, apart the order of the callback arguments, is that in jQuery the value is also available as context of the callback's call (this is why the value, less important, is only the second argument provided). This isn't really a major reason to prefer it unless you really like to avoid passing an argument to the function :
var product = 1;
$.each([1, 2, 3], function(){ product *= this });
Most often, you don't use both libraries, so you simply use the iterating function provided by the library you have.
If you happen to import both libraries, I would suggest to use the underscore function as
See source :
...
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With