In JS, doing a read access on undeclared variable gives reference exception.
I tried following code:
var obj = { };
console.log(obj.v1);
This prints undefined
console.log(v2);
While this throws exception.
What is the reason for different behavior? I was expecting exception in both cases as both v1 and v2 are undeclared.
EDIT: More confusing is the fact that if v2 was declared in global scope, it would have become property of window object. So does it not become similar to the case that I am accessing an undeclared property of window object? Same as case 1?
var obj = { };
console.log(obj.v1);
obj
is defined but it's property v1 doesn't exist, so output undefined
.
console.log(v2);
v2
is not declared so, output like Uncaught ReferenceError: ...
for window.v2
output is undefined
but for only v2
output is: ReferenceError
.
var foo = 1;
// Explicit global/window variable (new variable)
bar = 2;
// Implicit global/window variable (property of default global object)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With