Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between underscore js _.each method and _.invoke method

I am not able to understand the difference between underscore js methods _.each and _.invoke.
Both seems to invoke the function passed on each item.

Under which scenario shall I use _.each and _.invoke?

Please share the difference with some examples.

like image 404
Dinesh P.R. Avatar asked Nov 02 '12 11:11

Dinesh P.R.


1 Answers

No, they do different things. Have a look at their code!

  • each calls a given function with each element of a given object. You can additionally pass it a context on which the functions are applied. It acts like the native forEach on arrays.

    iterator.call(context, obj[i], i, obj)
    

    It does return undefined.

  • invoke usually gets a method name as a string, and looks up the method dynamically for each element of the given set. Then it applies the method on that element; and you additionally can pass it some arguments.

    (_.isFunction(method) ? method : obj[i][method]).apply(obj[i], args);
    

    It does return the results of the invocations, it basically does map.

like image 59
Bergi Avatar answered Oct 02 '22 15:10

Bergi