Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference between `_.forEach` and `$.each` [closed]

Tags:

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?

like image 574
Lorraine Bernard Avatar asked Dec 11 '12 16:12

Lorraine Bernard


People also ask

What is the difference between forEach and each?

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

What is the difference between map () and forEach ()?

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.

What is difference between map filter and forEach?

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.


2 Answers

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

  1. _.forEach it will be a bit faster as it uses the native Arrray.prototype.forEach in modern browsers.
  2. the this value is also different. jQuery's behavior doesn't follow the standard, underscore's does.
like image 157
antonjs Avatar answered Sep 21 '22 17:09

antonjs


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

  • it's the most similar to the standard ECMAScript function on arrays so you'll more easily migrate the day IE8 will be dead
  • it's more efficient as it uses the native function when it's available :

See source :

...
if (nativeForEach && obj.forEach === nativeForEach) {
     obj.forEach(iterator, context);
...
like image 21
Denys Séguret Avatar answered Sep 21 '22 17:09

Denys Séguret