How do I verify the existence of an object in JavaScript?
The following works:
if (!null)
alert(\"GOT HERE\");
But this throws a
zero and null are implicit pointers. If you arn't doing arithmetic, comparing, or printing '0' to screen there is no need to actually type it. Its implicit. As in implied. Typeof is also not required for the same reason. Watch.
if(obj) console.log("exists");
I didn't see request for a not or else there for it is not included as. As much as i love extra content which doesn't fit into the question. Lets keep it simple.
I've just tested the typeOf examples from above and none worked for me, so instead I've used this:
btnAdd = document.getElementById("elementNotLoadedYet");
if (btnAdd) {
btnAdd.textContent = "Some text here";
} else {
alert("not detected!");
}
You can use:
if (typeof objectName == 'object') {
//do something
}
There are a lot of half-truths here, so I thought I make some things clearer.
Actually you can't accurately tell if a variable exists (unless you want to wrap every second line into a try-catch block).
The reason is Javascript has this notorious value of undefined
which strikingly doesn't mean that the variable is not defined, or that it doesn't exist undefined !== not defined
var a;
alert(typeof a); // undefined (declared without a value)
alert(typeof b); // undefined (not declared)
So both a variable that exists and another one that doesn't can report you the undefined
type.
As for @Kevin's misconception, null == undefined
. It is due to type coercion, and it's the main reason why Crockford keeps telling everyone who is unsure of this kind of thing to always use strict equality operator ===
to test for possibly falsy values. null !== undefined
gives you what you might expect. Please also note, that foo != null
can be an effective way to check if a variable is neither undefined
nor null
. Of course you can be explicit, because it may help readability.
If you restrict the question to check if an object exists, typeof o == "object"
may be a good idea, except if you don't consider arrays objects, as this will also reported to be the type of object
which may leave you a bit confused. Not to mention that typeof null
will also give you object
which is simply wrong.
The primal area where you really should be careful about typeof
, undefined
, null
, unknown
and other misteries are host objects. They can't be trusted. They are free to do almost any dirty thing they want. So be careful with them, check for functionality if you can, because it's the only secure way to use a feature that may not even exist.
Or, you can all start using my exclusive exists() method instead and be able to do things considered impossible. i.e.:
Things like: exists("blabla")
, or even: exists("foreignObject.guessedProperty.guessNext.propertyNeeded")
are also possible...
for me this worked for a DOM-object:
if(document.getElementsById('IDname').length != 0 ){
alert("object exist");
}