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