Javascript null or default operator

A neat little trick I learnt from Ting is a way to check whether a value was null or undefined using the or operator (||).

It’s really simple. If valueThatMightBeEmpty has a value set, you get that value. If it is null you get the default. It’s just like the ?? operator in C#:

  1. var value = valueThatMightBeEmpty || defaultValue;

A real example

A really handy place to do this is event handling code. It’s a classically annoying bit of web development where the event information will be stored in a global variable called event for IE and in the first parameter passed to the event handler (I usually call it e) in other browsers.

So you might write some code that looks like this to get an event object that you can use in all browsers:

  1. if(!e)
  2.     e = event;

Instead you could just use the or operator (||) to check whether the variable was null and return a reference to the event object if it is:

  1. e = e || event;

Complete example

Posted on 09 Dec 08 by Helen Emerson (last updated on 09 Dec 08).
Filed under Javascript