Utilizing default values for function arguments
There are several ways to assign default values for function arguments. Below are the four most common methods, two of which have limitations depandant on what value is passed.
Simple Approach
if ( !param )
function test1(bar) {
if (!bar) {
bar = "Default Value";
}
alert(bar);
}
param = param || "default"
function test2(bar) {
bar = bar || "Default Value";
alert(bar);
}
These methods will use the default value for any argument that evaluates to false. This means they will incorrectly override 0 || false || '' || null in addition to undefined.
Tests
- Demo using onclick="test2();"
- Demo using onclick="test2(undefined);"
- Demo using onclick="test2(0);"
- Demo using onclick="test2('');"
- Demo using onclick="test2(null);"
- Demo using onclick="test2(false);"
- Demo using onclick="test2('hello');"
- Demo using onclick="test2(1);"
- Demo using onclick="test2({test:'foo'});"
- Demo using onclick="test2([1,2,3]);"
Preferred Approach
if ( bar === undefined )
function test3(bar) {
if (bar === undefined) {
bar = "Default Value";
}
alert(bar);
}
if ( typeof bar == 'undefined' )
function test4(bar) {
if (typeof bar == 'undefined') {
bar = "Default Value";
}
alert(bar);
}
These methods will only use the default value if no argument or undefined was passed.
Tests
- Demo using onclick="test4();"
- Demo using onclick="test4(undefined);"
- Demo using onclick="test4(0);"
- Demo using onclick="test4('');"
- Demo using onclick="test4(null);"
- Demo using onclick="test4(false);"
- Demo using onclick="test4('hello');"
- Demo using onclick="test4(1);"
- Demo using onclick="test4({test:'foo'});"
- Demo using onclick="test4([1,2,3]);"
Conclusion
As the simple approach methods can override potentially valid values, they should only be used if you know when and why they break.
My vote would be to use if (param === undefined), it just looks nicer.
"Know your input" - boki, 2005.
Acknowledgements
Thanks to Dashiva, boki, brainy and [Roosta] for help and support.