Categories:
Partners

Using named arguments in JavaScript functions

Credits: This tutorial is written by David Andersson (Liorean). Please see footnote for more information on author.

Normally, a JavaScript function takes an list of arguments, with the order of each argument predetermined. As an example, the parseInt() function takes two arguments, a string representing a number, and the radix of that number. You need to specify those in exactly that order, first a string, then the number, or at the very least, just the first argument. However, ponder a function where you wish to specify only the second argument, or both of them in arbitrary order - the deficiency of the JavaScript arguments model prohibits this. In this tutorial, I'll teach you how to modify JavaScript functions to accept named arguments, with which you can specify in any order, as named arguments don't rely on order, but instead their name when passing into functions.

JavaScript functions do not natively support naming arguments, so the simplest way to simulate this functionality is via object literals. Let me illustrate with a custom parseInt() function that can accept its two arguments in any order: 

JavaScript Function with Named Arguments
// Define function to take one "argument", which is in fact an object:
function fnParseInt( oArg ){ 
return parseInt( oArg.number, oArg.radix );
}

// Which you then call like this (pass in an object literal):
fnParseInt( { number : 'afy', radix : 36 } );

The key to the above is passing in an object literal as the function's sole parameter instead of separate, "authentic" parameter(s). Now, this is a pretty useless example, but it illustrates my point of creating a function that can accept arguments in any order and via a more intuitive name:value format. Such functions are much more robust than standard ones, not to mention user friendly in cases where the function takes on a lot of parameters.

Copyright 1997-2014 JavaScript Kit. NO PART may be reproduced without author's permission.