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

I can not understand the difference between underscore js methods _.each and _.invoke .
Both seem to call the function passed over each element.

In which scenario should I use _.each and _.invoke ?

Please share the difference with some examples.

+7
source share
1 answer

No, they do different things. Look at their code!

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

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

    It returns undefined.

  • invoke usually gets the method name as a string and dynamically searches for a method for each element of the given set. He then applies the method to this element; and you can also pass him some arguments.

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

    It returns the results of calls, mainly a map .

+9
source

All Articles