I happened upon something strange (at least to me), and maybe someone can elaborate on this for me:
const a = undefined;
const c = {};
/** this works correctly **/
console.log(a === undefined);
/** this does not throw an exception **/
console.log(c.someProperty === undefined);
/** this throws an exception, why? **/
console.log(b === undefined);
Just is in the example above, why is it, that if I want to check for an objects property, with === undefined
which was not defined everything is okay, but as soon as I try to check for a top-level variable for being defined, I am getting an error?
Here's a fiddle.
CodePudding user response:
The ECMAScript Language Specification states that accessing a nonexistent variable throws a ReferenceError
(see GetValue) while accessing a nonexistent property results in undefined
(see OrdinaryGet).
To check if a global variable is defined, you can use typeof
, which does not throw.
console.log(typeof b === 'undefined');
Top-level variables declared with var
also exist on the window
object, so you can use a property access too.
console.log(window.b === undefined);
CodePudding user response:
The thing is that b is not undefined, it is not even declared.You cannot call a variable that is not declared, be you can with one that is declared but undefined.
const a = undefined;
const b
const c = {};
console.log(a === undefined) //true
console.log(b === undefined) //true
console.log(c.someProperty === undefined) //true
console.log(typeof d === 'undefined') //true, it does not exist
try{
console.log(d)
} catch (e) {
console.log('error!')
} //error!