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 example above element variable gets value of document.body if null (undefined). Similarly index variable gets 0 value if undefined or null.

Posted on Sunday, December 12, 2010 by | Add Comment

New Comment

Your Name:
Email (for internal use only):
Code above:


Recent Tweets

  • Simon Ince's Blog: Hierarchies with HierarchyID in SQL 2008
  • Visual Studio 2010 WAS painfully slow - CodeProject

Valid HTML5