0% found this document useful (0 votes)
23K views

How To Check A Not Defined Variable in Javascript

There are several ways to check if a variable is defined or not defined in JavaScript. To check if a variable is null, use "if (null == yourvar)" or "if (null === yourvar)". To check if a variable exists in any scope, use "if (typeof yourvar != 'undefined')". To check if a variable exists in global scope, use "if (window['varname'] != undefined)". To check if a variable has a value stored in it, use "if (undefined != yourvar)" or "if (void 0 != yourvar)". To check if an object member exists, use "if ('membername' in object)" or "if (object.hasOwnProperty('member

Uploaded by

I@Sydney
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23K views

How To Check A Not Defined Variable in Javascript

There are several ways to check if a variable is defined or not defined in JavaScript. To check if a variable is null, use "if (null == yourvar)" or "if (null === yourvar)". To check if a variable exists in any scope, use "if (typeof yourvar != 'undefined')". To check if a variable exists in global scope, use "if (window['varname'] != undefined)". To check if a variable has a value stored in it, use "if (undefined != yourvar)" or "if (void 0 != yourvar)". To check if an object member exists, use "if ('membername' in object)" or "if (object.hasOwnProperty('member

Uploaded by

I@Sydney
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 1

How to check a not defined variable in

javascript

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:

if(variablename)

I probably forgot some method as well...

You might also like