I often have JavaScript functions with optional parameters. Instead of writing a long check like this:
if(param === null || param === undefined){
param = {};
}
I usually use the following syntax:
function doSomething(optionalParam, optionalCallback, optionalFlag){
optionalParam = optionalParam || {};
optionalParam["xyz"] = "value"; //Won't fail if the user didn't pass a value
optionalCallback = optionalCallback || function(){};
optionalCallback(); //If I need the function on 20 places, I don't have to insert a typeof-check everywhere
optionalFlag = optionalFlag || false;
}
The advantages are clear and I can deal with both undefined
and null
parameters.
This will, however, not work for optional flags that default to true:
someFlag = someFlag || true; //Will never evaluate to false.
Here's another example where I use that syntax:
function getValueOfIndex(idx){
return anArray[idx] || null; //Returns null if the index is out of bounds
}
How does the ||
operator work in my use case?
||
for all of these situations? Edit: I recognised that my last point (difference between null||undefined
and undefined||null
) should belong to a seperate question, so I removed it.
The general answer is that you can't use
parameter = parameter || default;
if the user should be able to pass an explicit parameter that's falsey, and that should take precedence over the default. In that case you need to test explicitly for undefined
:
parameter = typeof parameter == "undefined" ? default : parameter;
If the user should be able to pass an explicit undefined
value and have that take precedence (a very perverse thing to do), you'll need to test arguments.length
to determine how many arguments were passed, so you can default only the remainder.