Daily Tips & Tricks for Web Enthusiasts

Default Values for Arguments

If you don’t need to support Internet Explorer, all of the other major browsers allow you to specify default arguments in your JavaScript functions like this:

function foo(argument = 'default') {
    // ...
}

With this code, if foo() is called and argument is undefined (either because the argument is missing or because it is explicitly set to undefined), the default value of 'default' will be assigned to argument.

Now, if you do need to support older browsers like IE, you may find yourself writing something like this:

function foo(argument) {
    if (!argument) {
        argument = 'default';
    }

    // ...
}

That works, but this approach will get out of hand pretty quickly as the number of arguments increases. I’ve got good news, though! There’s a better way:

function foo(argument) {
    argument = argument || 'default';

    // ...
}

These last two code snippets function in exactly the same way, but the second version is shorter and easier to maintain.

This version works because the || operator (which is usually used in if statements) will first check to see if what’s to the left can be converted to true and, if it can, will return whatever’s on the left. Otherwise the value on the right is returned. This behavior is called short circuiting, and you can read more about it on MDN if you’re curious about the specifics.

This version also has the advantage of being concise without being hard to understand. You can read this as, “Make the argument variable equal to the original argument value if it exists, or use the default value otherwise.”

One word of warning: This second method doesn’t behave exactly like the native version described at the beginning of this tip. The native version of default argument value assignment checks to see if argument values are undefined or not, but the second method checks if they convert to true or not. That means values that convert to false, like an empty string ('') or a zero (0), will trigger the default value.

In other words, calling foo(0) using the first code snippet above would assign 0 to argument inside the function, whereas calling foo(0) using the second or third code snippets would assign 'default' to argument instead (because 0 converts to false and, thus, triggers the default value assignment).