Dinesh P.R.
Dinesh P.R.

Reputation: 7236

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.

Upvotes: 7

Views: 5094

Answers (1)

Bergi
Bergi

Reputation: 664610

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.

Upvotes: 9

Related Questions