Setting Default Variable Value in JavaScript

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

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.

The Sexier Code

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

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

  • Subhayu Mukherji


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

    aah the pains of coding in an outdated language :(

    • Shamasis Bhattacharya

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

      The “OR” operator would work.

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

  • Binaek Sarkar


  • kenkku

    Are you serious?! That’s sexy?? I’d rather call that unintelligible spaghetti. Either you have to know what it means or wrap your head around that complicated statement, which makes this VERY error-prone. I hope nobody actually uses this. Yuck.

    • Shamasis Bhattacharya

      With great power comes responsibility. :-) True JS is always not for the faint hearted. 😉