Search code examples
javascriptoperatorsdefault-parameters

Can I always use `||` to assign default parameter values?


Optional Parameters

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.

Return values

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
}

My Question:

How does the || operator work in my use case?

  • Can I use || for all of these situations?
  • Is there any reason not to use it?
  • Are there any other types or values where this syntax will fail?

Edit: I recognised that my last point (difference between null||undefined and undefined||null) should belong to a seperate question, so I removed it.


Solution

  • 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.