Javascript Detect Null Object

There are many methods to check if an object is null in javascript, this post gives most of the options that can used to detect this.

Well, first of all, in JavaScript null is an object. There’s another
value for things that don’t exist, undefined. The DOM returns null for
almost all cases where it fails to find some structure in the
document, but in JavaScript itself undefined is the value used.

Second, no, they are not directly equivalent.
If you really want to check for null, do:

if (null == yourvar) // with casting
if (null === yourvar) // without casting

If you want to check if a variable exist

if (typeof yourvar != ‘undefined’) // Any scope
if (window[‘varname’] != undefined) // Global scope
if (window[‘varname’] != void 0) // Old browsers

If you know the variable exists but don’t know if there’s any value
stored in it:

if (undefined != yourvar)
if (void 0 != yourvar) // for older browsers

If you want to know if a member exists independent of whether it has
been assigned a value or not:

if (‘membername’ in object) // With inheritance
if (object.hasOwnProperty(‘membername’)) // Without inheritance

If you want to to know whether a variable autocasts to true:



8 Responses

  1. Hi … thank you for the article. It good stuff.

  2. Excellent information. Thank you for making a confusing subject much more understandable.

  3. ok thx

  4. Hello webmaster
    I would like to share with you a link to your site
    write me here

  5. woman’s 🙂

  6. What does === mean? I’ve never seen that before.
    Can point to any documentation about it?

    • I dont know if === is in JavaScript likely it is. I know its in PHP. With PHP === means the difference between A and B are not only the same information but they are the same datatype as well. Where as == means A and B are the same information but not necessarily the same datatype.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: