Posted By: Anonymous
I wanted to check whether the variable is defined or not. For example, the following throws a not-defined error
alert( x );
How can I catch this error?
null is an object. There’s another value for things that don’t exist,
undefined. The DOM returns
undefined is the value used.
Second, no, there is not a direct equivalent. If you really want to check for specifically for
if (yourvar === null) // Does not execute if yourvar is `undefined`
If you want to check if a variable exists, that can only be done with
typeof will treat an undeclared variable and a variable declared with the value of
undefined as equivalent.
But, to check if a variable is declared and is not
if (yourvar !== undefined) // Any scope
Previously, it was necessary to use the
typeof operator to check for undefined safely, because it was possible to reassign
undefined just like a variable. The old way looked like this:
if (typeof yourvar !== 'undefined') // Any scope
The issue of
undefined being re-assignable was fixed in ECMAScript 5, which was released in 2009. You can now safely use
!== to test for
undefined without using
undefined has been read-only for some time.
If you want to know if a member exists independent but don’t care what its value is:
if ('membername' in object) // With inheritance if (object.hasOwnProperty('membername')) // Without inheritance
If you want to to know whether a variable is truthy: