Problem
In JavaScript, how can I check if an object exists?
The following works:
if (!null)
alert("GOT HERE");
However, this results in an Error:
if (!maybeObject)
alert("GOT HERE");
The Error:
Asked by Yarin
Solution #1
On undefined variables, the typeof operator is safe to employ.
typeof will return something other than undefined if it has been given any value, including null. typeof returns a string every time.
Therefore
if (typeof maybeObject != "undefined") {
alert("GOT THERE");
}
Answered by JAL
Solution #2
There are a lot of half-truths here, so I figured I’d clarify a few things.
You can’t tell if a variable exists with any accuracy (unless you want to wrap every second line into a try-catch block).
The reason for this is because Javascript has the infamous undefined value, which does not imply that the variable is not defined or that it does not exist undefined! == undefinable
var a;
alert(typeof a); // undefined (declared without a value)
alert(typeof b); // undefined (not declared)
As a result, both existing and non-existing variables can report the undefined type.
In response to @Kevin’s misunderstanding, null == undefined. It’s because of type coercion, which is why Crockford usually advises anyone who isn’t sure about something like this to use the strict equality operator === to check for potentially false values. What null!== undefined offers you is exactly what you’d expect. Please keep in mind that using foo!= null to verify if a variable is neither undefined nor null might be quite useful. Of course, you can be clear if you think it will improve readability.
If you only want to check if an object exists, typeof o == “object” could be a reasonable choice, unless you don’t consider arrays to be objects, in which case this will also be reported as the type of object, which could be confusing. Not to add that typeof null will return an object, which is completely incorrect.
The primary area where typeof, undefined, null, unknown, and other enigmas should be avoided is host objects. They are untrustworthy. They are free to do practically anything they desire with their bodies. So be cautious with them, and if possible, test for functionality, as this is the only safe method to use a feature that may or may not exist.
Answered by gblazex
Solution #3
You can use:
if (typeof objectName == 'object') {
//do something
}
Answered by Calvin
Solution #4
Two ways.
You can use typeof: to check for a local object.
if (typeof object !== "undefined") {}
By analyzing the window object, you may check for a global object (one defined on the global scope):
if (window.FormData) {}
Answered by superluminary
Solution #5
You can use if (!window.maybeObject) if it’s a global object.
Answered by Nikita Rybak
Post is based on https://stackoverflow.com/questions/4186906/check-if-object-exists-in-javascript