The invoke function is a utility method that is designed to execute the same property function for each element of the collection provided.

When creating web apps, one of the most helpful Javascript libraries is Lo-Dash. Lo-Dash is a utility library (like Underscore.js) that makes manipulation, iteration and filtering of JS arrays and opjects easy as it should be. However, including such libraries when you need only one method is overkill.

The invoke method is pretty simple:

function invoke (collection, fn, args) {
  var i, j;
  if(collection.length) {
      // the collection is an array or an array like object
      for(i = 0, j = collection.length; i < j; i++) {
          collection[i][fn].apply(collection[i], args);
  } else {
      // the collection is an object
      for (i in collection) {
          if(collection.hasOwnProperty(i)) {
              collection[i][fn].apply(collection[i], args);

This method is really useful when you have multiple instances of the same “class” and you need to call the same method on all of them.

// Example of module 
var Counter = function () {
  var count; // private
  return {
      set: function (a) { // public method
          count = a;

// Group instances together
var group = {
  foo: new Counter(),
  bar: new Counter()

// later on execute the update function on all instances
invoke(group, 'set', [0]);
// now the variable count is 0 on all of them