Reputation: 424
I 've inspected different behavior for undefined/undeclared variables in javascript .For example :
var obj = {};
console.log(x);//Error
console.debug(obj.x) ;//undefined
My question is though c and obj.x both are not declared or defined then why I'm getting diff behavior? Am I missing something? How should I track which variable is already exist or not?
Upvotes: 1
Views: 75
Reputation: 140228
You can't reference an undeclared variable without it being an error, unless you are assigning it in non-strict mode then it becomes an implicit global. Still error in strict mode though.
Trying to access object properties is not the same as trying to access variables, though you can access global variables from window
:
x; //referenceerror
window.x; //undefined, no reference error
window.x
vs x
in this situation for example:
var x = 5;
(function(){
var x = 3;
x === 3; //We cannot access the 5
window.x === 5 //Only window.x will do it here
})()
Upvotes: 1
Reputation: 90776
If you try to access an undefined variable, you will get an error, which is generally a good thing since it allows you to find bugs more easily.
If you want to find out if a variable is defined or not, you can check its type like this:
console.info(typeof x === "undefined" ? "<undefined!>" : x);
In the case of obj.x
, x
is a property not a variable and you can always look up a property because of the dynamic nature of JavaScript objects.
Upvotes: 1
Reputation: 6911
This is expected behavior in javascript. If you are accessing an undeclared variable (x), an error occurs because engine doesn't know what you are trying to access.
On the other hand, objects have some sort of a dual nature. It acts as both an object and an array, and javascript allows you to try to access member of an array even if member under given key doesn't exist. If there is no key under specified value, you will get back undefined
.
I.e. following two lines are equivalent
console.log(obj.x);
and
console.log(obj["x"]);
You would only get error if you try to access member of non existing variable. E.g.
console.log(obj.x.x);
Upvotes: 1