JavaScirpt functions: optional parameters (default values)

The current JavaScript specification doesn't support function parameter default values right out the box, but as always there are ways.

Where as in some other programming languages, parameter default values might be expressed like so:

function some_function($some_param = true) {
    // ...
}

In JavaScript that’s not possible, the parameter needs to be treated like any old variable.

Simplified example function:

var colorifyer = function(element, color) {
    documnet.getElementBtId(element).style.color = color;
}

That color parameter needs a default value. There’s few ways to do that, behold.

Simple, limited method

The following methods work if the parameter is never false.

This reminds the user that the parameter is needed:

var colorifyer = function(element, color) {
    if (!color) {
        // Notify the user
        console.log("Gooby plz, give it a color!");
        // Then die
        return false;
    }
    documnet.getElementBtId(element).style.color = color;
}

The following, friendlier example, gives it a default value of Pink:

var colorifyer = function(element, color) {
    // Default to Pink
    color || (color = 'Pink');
    documnet.getElementBtId(element).style.color = color;
}

A really primitive example: if just anything is passed to the function, it’s possible to check the length of the arguments object:

var someFunction = function() {
    if (arguments.length) {
        console.log(arguments); 
    } else {
        console.log('Nothing was passed to the function')
    }
}

These all will fail if the parameter is needed to be false, 0, or any falsy value. But it’s hard to beat the simplicity of color || (color = 'Pink');.

The more robust method

If the parameter might also be false, check the type first with typeof:

var colorifyer = function(element, color) {
    // If not undefined, then use color, if undefined, use Pink
    color = (typeof color !== 'undefined') ? color : 'Pink';
    documnet.getElementBtId(element).style.color = color;
}

The future

ECMAScript 6 (the new JavaScript language specification) supports default values out the box:

var colorifyer = function(element, color = 'BADA55') {
    documnet.getElementBtId(element).style.color = color;
}

This is currently only supported by FireFox. Here’s an MDN article on it.

Takeaways

JavaScript is at time a sparse language, witch is good in the sense that it forces creative use of the language.

Club-Mate, the beverage → club-mate.fi