It has been a while since I wrote a JavaScript utility function so a few minutes ago, I had the idea to create a function which will allow you to set the default value of a parameter for any given function. After writing the following function, I thought about the fact that the next version of jPaq already has this partially defined:


Function.prototype.defaultTo = function() {
  var fn = this, defaults = arguments;
  return function() {
    var args = arguments,
      len = arguments.length,
      newArgs = [].slice.call(defaults, 0),
      overrideAll = args[len - 1] === undefined;
    for(var i = 0; i < len; i++) {
      if(overrideAll || args[i] !== undefined) {
        newArgs[i] = args[i];
      }
    }
    return fn.apply(this, newArgs);
  };
};

The reason this function is different is because it will allow you to override defaults with any value—even undefined. Let’s see a few examples that prove that this works the way I claim it does:


// A function that takes one value and simply spits it back out.
// If nothing is passed in, false will be returned.
var inOut = function(value) {
  return value;
}.defaultTo(false);

// Test it out:
alert(inOut());  // returns false
alert(inOut(Math.PI));  // returns the value of PI
alert(inOut("Hello world!!!"));  // returns "Hello world!!!"
alert(inOut(null));  // returns null
alert(inOut(undefined));  // returns undefined

If you try out the above code after using the definition for the defaultTo(), you will find that every value that was passed in was also returned. In addition, when nothing was passed in, false was returned as specified by the default. The one question that may linger is, how is it that you can pass in undefined and the default is still overridden? The answer is that whenever undefined is passed in as the last argument, all defaults are overridden with the specified parameters. Now that you no the ins and outs of this function, you can start setting defaults for all of your functions without a problem.


Leave a Reply

Your email address will not be published. Required fields are marked *