Sunday, August 19, 2018

How to check a not-defined variable in JavaScript




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?


Answer



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, there is not a direct equivalent. If you really want to check for specifically for null, do:




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 try/catch, since 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 undefined:



if (typeof yourvar !== 'undefined') // Any scope



Beware, this is nonsense, because there could be a variable with name undefined:



if (yourvar !== undefined)


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:



if (yourvar)


Source


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...