Reputation: 6289
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?
Upvotes: 1
Views: 138
Reputation:
On if statement, while statement, etc, type value of null, 0(integer of 0), undefined, false(boolean of false), and NaN(not a number) is counted as false,
else counted as true, E.g. integer except 0, true(boolean of true), string, Etc...
So when you executing if (obj){...}
the obj return an object value type, which is not one of the 5 value that counted as false, and then will execute the if statement.
When code if (obj.a){...}
executed, the obj.a return a string, and then counted as true
when code if(obj.b){...}
executed, the obj.b return an undefined value type, and then counted as false and will not execute if statement, but it execute the else statement. And it also occured for executing if(newObj){...}
Upvotes: 1
Reputation: 651
It's because You are already defined obj.So checking if obj has b never fire reference error. because obj.b
has special value called undefined this is automatically handled by JavaScript. So you can check undefined keys by if(obj.b===undefined)
. If you want check an object is undefined or not you can use if( typeof newObj==='undefined')
.
Upvotes: 0
Reputation: 486
Use
'undefined' === typeof newObj
to check whether it exists or not, my friend.
Upvotes: 0
Reputation: 48
There is nothing as 'newObj' in memory so it does throw Uncaught ReferenceError.
While we have 'obj' in our memory. So when you ask 'obj.b' then it search for key 'b' in dictionary 'obj'. And so it doesn't have value then it will be undefined.
Thanks
Upvotes: 0
Reputation: 4156
Because there is no such a thing as newObj. There is no object. The variable itself was never initialized, therefore it does not exists.
The undefined is a special value, which can be assigned to a variable. But when there is no variable defined, then ReferenceError is thrown.
Accessing obj.b means that you are already have an object referenced by variable named obj. This object is basically a hash, and it can have many properties. When property does not exist or its value is undefined, then it return undefined.
See MDN - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined
Upvotes: 1