Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does reference exception does not come in case of undeclared object properties? [duplicate]

Tags:

javascript

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?

like image 389
tryingToLearn Avatar asked Nov 02 '17 12:11

tryingToLearn


1 Answers

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)
like image 117
Sajib Khan Avatar answered Oct 23 '22 11:10

Sajib Khan