We build Web & Mobile Applications.

< All Articles

Prototype, emptyFunction and callbacks

Let’s say we have a JavaScript function that looks like this:

function plot(options) {
  options = options || {};
  this.onUpdate = options.onUpdate;

  //
  // more code to do something interesting
  //
}

Here the plot method allows an optional onUpdate callback to be specified. The problem is that every time we should use the callback, we have to check that it was actually provided, like this:

if (typeof(this.onUpdate) == 'function') this.onUpdate();

Prototype provides the isFunction method, which tidies up the code a little:

if (Object.isFunction(this.onUpdate)) this.onUpdate();

But I think a nicer way to handle this is to use the emptyFunction method during the initialisation of the callback. emptyFunction is pretty much what you’d expect: a function that’ll swallow any arguments you call it with, does nothing and returns nothing. This means that when we want to use the callback we can just call it without having to worry about whether or not we should, for example:

function plot(options) {
  options = options || {};
  this.onUpdate = options.onUpdate || Prototype.emptyFunction;

  //
  // more code to do something interesting
  //

  // Call the callback
  this.onUpdate();
}
Updated on 07 February 2019
First published by Rob Anderton on 09 April 2009
© Rob Anderton 2019
"Prototype, emptyFunction and callbacks" by Rob Anderton at TheWebFellas is licensed under a Creative Commons Attribution 4.0 International License.