Why does the reference exception not occur in the case of undeclared properties of the object?

In JS, doing a read for an undeclared variable gives a reference exception.

I tried the following code:

var obj = { };
console.log(obj.v1);

Prints undefined

console.log(v2);

So far this has thrown an exception.

What is the reason for the different behavior? I was expecting exceptions in both cases since v1 and v2 are not declared.

EDIT: More confusing is the fact that if v2 was declared in the global scope, it would become a property of the window object. Doesn't this look like the case when I refer to an undeclared property of a window object? Same as case 1?

+6
source share
1 answer
var obj = { };

console.log(obj.v1);

obj, but its property v1 does not exist, therefore print undefined.


console.log(v2);

v2 not declared so conclusion as Uncaught ReferenceError: ...


window.v2 undefined, v2 : ReferenceError.

var foo = 1;
// Explicit global/window variable (new variable)

bar = 2;
// Implicit global/window variable (property of default global object)
+1

All Articles