github linkedin rss
JavaScript: What is void 0 and why use it?
Mar 22, 2014

If you’ve been around JavaScript for a while you might be familiar with the term “undefined”. Basically if you don’t assign a value to a variable it will get the value undefined.

There are probably places in your code where you’ll want to see if a variable is undefined, to make sure that you can use it. Your code might look something like this:

What you might not know is that it’s possible to redefine undefined, which will cause your code to break. Consider the case where you include a script on your site, which by misstake or lack of knowledge assigns a value to undefined.

This is where void 0 comes in. Instead of comparing to undefined you could compare to void 0 which is not possible to redefine, it will always return undefined.


One could also check if a variable is undefined through the type of operator, which actually might be the best idea: It won’t be affected by a redefined undefined, and will not throw a ReferenceError if the variable is not declared.

A common practise is to encapsulate your code into a self invoking function, where you make sure that undefined is acually undefined.

Back to posts