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.
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.
You can use:
You can use the
!
operator twice!!
:Or one time
!
for not exists:What is the !! (not not) operator in JavaScript?
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 that's a global object, you can use
if (!window.maybeObject)
I've just tested the typeOf examples from above and none worked for me, so instead I've used this: