[thelist] What's the most reliable way to check a javascript null?

liorean liorean at gmail.com
Thu Feb 17 16:49:13 CST 2005

On Thu, 17 Feb 2005 11:56:15 -0800, Jonathan Dillon
<jdillon at boehm-ritter.com> wrote:
> Howdy all:
> I'm wondering if, in javascript: [snip]
> ... are equivalent... And whether one is "best practice" or whether one
> needs several of these tests to accommodate all browsers.
> I'm writing a test case to determine whether a javascript variable exists.
> Any thoughts?

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:


I probably forgot some method as well...
David "liorean" Andersson

More information about the thelist mailing list