Null coalescing operator for JavaScript

Very often in javascript, some function parameters are optional. So, code like this become needed:

if (typeof something == "undefined")
    alert("something is undefined");

However, there is a better, slicker solution. This is a null coalescing operator in javascript “terms”:

function DoSomething(element)
    element = element || document.body;

function DoSomething(index)
    index = index || 0;

In the example above the element, the variable gets the value of document.body if null (undefined). Similarly index variable gets a 0 value if undefined or null.

Posted on May 12, 2010 by