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.
Method 1: Using the typeof operator The typeof operator returns the type of the variable on which it is called as a string. The return string for any object that does not exist is “undefined”. This can be used to check if an object exists or not, as a non-existing object will always return “undefined”.
Using the indexOf() Method JavaScript's indexOf() method will return the index of the first instance of an element in the array. If the element does not exist then, -1 is returned.
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"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With