Tuesday, January 03, 2012

Default Parameters for Javascript Functions

In PHP, you simple add "argument=false".

function getData(br, year=false) {}

In Javascript:

function getData(br,year) {
  year = (typeof year == 'undefined') ? false : year;
$('Data').load('/Data/getData/' + br + '/' + year);
} 

1 comment:

chris-west said...

You could also extend the JavaScript prototype for functions in order to achieve a simpler version of setting default parameters. I explain how to achieve the following here on my blog:
// A function that takes one value and simply spits it back out.
// If nothing is passed in, false will be returned.
var inOut = function(value) {
return value;
}.defaultTo(false);

// Test it out:
alert(inOut()); // returns false
alert(inOut(Math.PI)); // returns the value of PI
alert(inOut("Hello world!!!")); // returns "Hello world!!!"
alert(inOut(null)); // returns null
alert(inOut(undefined)); // returns undefined