Vishful thinking…

Writing better javascript – Part 2

Posted in javascript by viswaug on November 18, 2008

If you find yourself writing code like below often enough

test = new Array();

then you might be able to delay the onset of carpal tunnel by using the syntax below.

test = test || new Array();

The ‘||’ can be used kind of like the null coalescing operator for JavaScript. The above syntax will come in real handy when you want to set some default values for optional arguments in JavaScript functions.

Update: watch out when using the above syntax for assigning default values for boolean and number argument types. Even though false and 0 are valid arguments, they will still evaluate to falsey and end up taking the default value.


3 Responses

Subscribe to comments with RSS.

  1. Rob Coup said, on November 18, 2008 at 8:56 pm

    || is the logical OR operator in Javascript, so you need to be a little bit wary of using it for default values.

    Any “falsey” value (false, "", 0, NaN, undefined, null, …) will cause the second option to be taken.

    So, code like this won’t do what you expect:

    function foo(/*optional Boolean*/isHappy) {
    var happy = isHappy || true;

    In the above case, if you pass in nothing, happy==true (good). If you pass in true, happy==true (good). But if you pass in false, happy==true (bad). This is particularly prevalent for Boolean and Number parameters. Here’s a solution:

    function foo(/*optional Boolean*/isHappy) {
    var happy = (typeof(isHappy)==="undefined") ? true : false;

    HTH 🙂

  2. viswaug said, on November 18, 2008 at 9:52 pm

    Hi Rob,

    Thank you for that suggestion. I actually ran the scenario you had pointed out a couple of weeks ago when I was passing in the valid value of zero and my default was getting used. So, i went with

    (index || index === 0) || default;

    But I like your solution.


  3. Rob Coup said, on November 19, 2008 at 6:33 am

    Except there’s a bug in it, and it’s unnecessarily verbose 🙂

    var happy = (isHappy === undefined) ? true : isHappy;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: