Functions With Named Parameters


Part 3.1


Create functions with named parameters in JavaScript

JavaScript is quite forgiving about function parameters - pass too many and they will be ignored; pass too few and the absent ones will just be undefined. However it's sometimes useful to pass parameters to a function by name.

Here's a function which has a few parameters. It does some dodgy formatting on some text based on the parameters passed in.

var format = function (text, splitParagraphs, color, emphasis, strong) {

    if (splitParagraphs) {
        text = text.replace(/([\.\?:])/g, "$1<br /><br />");
    }
    
    if (emphasis) {
        text = "<em>" + text + "</em>";
    }
    
    if (strong) {
        text = "<strong>" + text + "</strong>";
    }
    
    if (color) {
        text = "<div style=\"color: " + color + ";\">" + text + "</div>";   
    }
    
    return text;    
};

When you call the function, you have to make sure the parameters are in the right order, which is a bit horrible:


var result = format(text, true, "Red", true, true);

There must be a better way to pass those parameters in!

Using an object as the function parameter

Here's a different way of writing the function. It now takes only two parameters, one of which is an object containing the options:

var format = function (text, options) {

    if (options.splitParagraphs) {
        text = text.replace(/([\.\?:])/g, "$1<br /><br />");
    }
    
    if (options.emphasis) {
        text = "<em>" + text + "</em>";
    }
    
    if (options.strong) {
        text = "<strong>" + text + "</strong>";
    }
    
    if (options.color) {
        text = "<div style=\"color: " + options.color + ";\">" + text + "</div>";   
    }
    
    return text;    
};

It can now be called like this:


var result = format(text, { 

    splitParagraphs: true,
    color: "Red",
    emphasis: true,
    strong: true
});

The first parameter is the text, and the second parameter is a JavaScript object:


{
    splitParagraphs: true,
    color: "Red",
    emphasis: true,
    strong: true
}

This makes it clearer which parameter is which, plus you can omit parameters that aren't needed.

One example where this is used is the jQuery.ajax function, which takes a URL and a settings object.

To simulate named parameters, you can write a function so that it takes an object instead of multiple parameters.