This may be elementary javascript question but I'd like to understand how js works on the inside.
const obj = { a: 'a'};
if(obj)
console.log('obj is not undefined');
else
console.log('obj is UNDEFINED');
if(obj.a)
console.log('obj.a is not undefined');
else
console.log('obj.a is UNDEFINED');
if(obj.b)
console.log('obj.b is not undefined');
else
console.log('obj.b is UNDEFINED');
if(newObj)
console.log('newObj is not undefined');
else
console.log('newObj is UNDEFINED');
The output I get when I execute these statements is
obj is not undefined
obj.a is not undefined
obj.b is UNDEFINED
Uncaught ReferenceError: newObj is not defined
Why is newObj throwing ReferenceError and obj.b is not throwing any error?
obj.blooks for a property in an already defined object. If the property is not found you getundefined.newObjis not defined in your code and the script has no idea what isnewObj, so you get an error.objinobj.bexists, whereas you never declared a variable fornewObj. You would get the same error forobj.b.x. And you will get undefined forwindow.newObj.