Default arguments in JavaScript
Posted: July 30th, 2011 | Author: shesek | Filed under: Javascript | Tags: default arguments, function arguments | No Comments »I’ve thought today on a nice and clean way of handling default function arguments in JavaScript. Because the arguments object in JavaScript defines getters and setters that also interact with the functions’s formal arguments, changing its values also changes the value of the local argument variables. For example:
function foo(bar) {
arguments[0] = "baz";
alert(bar); // bar is now "baz", not "qux"
}
foo("qux");
What that means is that we can pass the arguments object to another function, which can take care of setting default values and by that also modify our local argument variables:
window.setDefault = function (args) {
for (var i = args.length + 1; i<arguments.length; i++) {
args[i-1] = arguments[i];
}
};
// Minified:
// window.setDefault=function(a){for(var b=a.length+1;b<arguments.length;b++)a[b-1]=arguments[b]}
Than, to use it:
function foo(bar, baz, qux) {
setDefault(arguments, "bar", "baz", "qux");
console.log(bar, baz, qux); // "a", "baz", "qux"
}
foo("a");