Check if JavaScript variable is undefined

Share on:

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:

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

If you want to check if a variable exist

1    if (typeof yourvar != 'undefined') // Any scope
2    if (window['varname'] != undefined) // Global scope
3    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:

1    if (undefined != yourvar)
2    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:

1    if ('membername' in object) // With inheritance
2    if (object.hasOwnProperty('membername')) // Without inheritance

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

1    if(variablename)

Source: http://lists.evolt.org/archive/Week-of-Mon-20050214/099714.html