How to check a not-defined variable in JavaScript

Source: https://stackoverflow.com/questions/858181/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, 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
If you know the variable exists, and want to check whether there's any value stored in it:
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)

Không có nhận xét nào:

Cold Turkey Blocker

 https://superuser.com/questions/1366153/how-to-get-rid-of-cold-turkey-website-blocker-get-around-the-block Very old question, but still wan...