Default Parameter Values in Javascript

EDIT: check out the cross-browser version: https://gist.github.com/1336141

Some time ago I talked about default parameter values in Javascript. I always use this form:

function (a, b){
  a = a || 'default value 1';
  b = b || 'default value 2';
}

We can use the || (or) operator which returns the second expression if the first can’t be converted to true. This is good enough, and gets the job done. However, some people argue that it “contaminates” the body of the function. Personally, I think it doesn’t matter much, but abozhilov came up with a nice way to do default parameter values:

function func(a, f) {
    return function (args) {
        args.__proto__ = a;
        f.call(this, args);
    };
};


var f = func({foo : 10, bar : 20}, function (args) {
    print(args.foo, args.bar);
});

f({}); //10 20
f({foo : 50}); //50 20
f({foo : 50, bar : 50}); //50 50

There is one little problem, __proto__ is not available in all browsers, but that can be solved easily once you know what __proto__ is.

Personally I don’t like the way you have to define your functions:

var f = func({foo : 10, bar : 20}, function (args) {
    print(args.foo, args.bar);
});

It also forces you to use an object as parameter and wrap all your real parameters inside that object. I don’t like that.

However, the most important thing to note here is that this is nonetheless a very clever way to solve a problem, and it demonstrates the flexibility of javascript, and why it is a great language.

I first heard of this method a while ago via twitter. The original gist is at https://gist.github.com/1333507. Some of the comments there are worth reading.

2 thoughts on “Default Parameter Values in Javascript

  1. You could also extend the JavaScript prototype for functions in order to achieve a simpler version of setting default parameters. I explain how to achieve the following here on my blog:
    // 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

    • That is another way to do it. Very clever, I think. IT just demonstrates what a lot of people say: Javascript is a very powerful and versatile language.

      Thanks for sharing with us.

Comments are closed.