Setting Default Variable Value in JavaScript

September 10, 2011 · 3 comments   1,029 views

in Technical Publications

Often, there are conditions where we need to provide a default value of a variable if it is undefined. As a case study, we will take up the situation, where we are passing a Boolean value to function and if the input is true, some action has to be taken. In case someone does not pass any value, the input is assumed to be true.

The Ordinary Code

var foo = function (param) {
    var actionable = param;
    if (param === undefined) {
        actionable = true;
    }
    if (actionable) {
        // do something
    }
    if (actionable) {
        // again do something
    }
};

Another way to do the above in case we do not intend to re use what action we took is to simply do a composite check of the parameter.
var foo = function (param) {
    if (param === undefined || param === true) {
        // do something
    }
};

The Sexier Code

Nevertheless, there is always a scope to write this code in a more compact way.

  1. var foo = function (param) {
  2.     var actionable = param === undefined &&
  3.             true || param;
  4.  
  5.     if (actionable) {
  6.         // do something
  7.     }
  8. };

The very cryptic first two lines of the above code does the trick of the whole if-block.

  • Subhayu Mukherji

    naice…

    works for javascript….do you have something similar for vbscript?

    aah the pains of coding in an outdated language :(

    • http://www.shamasis.net/ Shamasis Bhattacharya

      For VBS, it may not appear as straightforward as JS.

      The “OR” operator would work.

    • http://www.shamasis.net Shamasis Bhattacharya

      Well… for vbscript, this type of syntax is possible. I remember using the OR keyword to assign default value to classic ASP variables.