JavaScript: Creating a Function with a Callback

Something I seem to do a lot of when writing JavaScript is creating callback functions. I like them, they help with execution order, and promises aren’t supported enough for me to make the jump over to them quite yet without a reliable polyfill (although they’re very nice). As in anything you need to careful when using callbacks or you’ll find yourself in, “callback hell,” as they say (there’s also coming called, “promise hell,” so you’re doomed either way if you abuseĀ them).

Here’s a quick template for creating a method with a callback. Nothing fancy, just a helpful little code snippet I hope you enjoy.

// Always namespacing!
varĀ App = {

  method : function (value, callback) {

    // just doing something generic so we know the method worked

    // make sure the callback argument is a function before calling it
    if (typeof callback === 'function') {

      // call the function this );

    } // end if
  } // end method()

} // end App

// call the method with a callback
App.method('Hey there', function(){
  // this is the callback function
  console.log('callback was executed!');

}); // end method call

Remember, don’t abuse the callback.