Check if object exists in JavaScript

Yarin picture Yarin · Nov 15, 2010 · Viewed 564.3k times · Source

How do I verify the existence of an object in JavaScript?

The following works:

if (!null)
   alert("GOT HERE");

But this throws an Error:

if (!maybeObject)
   alert("GOT HERE");

The Error:

maybeObject is not defined.

Answer

JAL picture JAL · Nov 15, 2010

You can safely use the typeof operator on undefined variables.

If it has been assigned any value, including null, typeof will return something other than undefined. typeof always returns a string.

Therefore

if (typeof maybeObject != "undefined") {
   alert("GOT THERE");
}