7

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.

1 Answer 1

9

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.