How do I verify the existence of an object in JavaScript?
The following works:
if (!null)
alert(\"GOT HERE\");
But this throws a
If that's a global object, you can use if (!window.maybeObject)
if (maybeObject !== undefined)
alert("Got here!");
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 care about its existence only ( has it been declared ? ), the approved answer is enough :
if (typeof maybeObject != "undefined") {
alert("GOT THERE");
}
If you care about it having an actual value, you should add:
if (typeof maybeObject != "undefined" && maybeObject != null ) {
alert("GOT THERE");
}
As typeof( null ) == "object"
e.g. bar = { x: 1, y: 2, z: null}
typeof( bar.z ) == "object"
typeof( bar.not_present ) == "undefined"
this way you check that it's neither null
or undefined
, and since typeof
does not error if value does not exist plus &&
short circuits, you will never get a run-time error.
Personally, I'd suggest adding a helper fn somewhere (and let's not trust typeof()
):
function exists(data){
data !== null && data !== undefined
}
if( exists( maybeObject ) ){
alert("Got here!");
}
Think it's easiest like this
if(myobject_or_myvar)
alert('it exists');
else
alert("what the hell you'll talking about");
I used to just do a if(maybeObject)
as the null check in my javascripts.
if(maybeObject){
alert("GOT HERE");
}
So only if maybeObject
- is an object, the alert would be shown.
I have an example in my site.
https://sites.google.com/site/javaerrorsandsolutions/home/javascript-dynamic-checkboxes