Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does accessing a non-existent object property result in `undefined` instead of throwing a `ReferenceError`?

When I try to use an undeclared variable I get ReferenceError:

console.log(a); // Uncaught ReferenceError: a is not defined

I could use a variable first and define it later and it won’t be a problem due to hoisting.

console.log(a); // undefined

var a;

But when I declare an object why would the execution context let me use any property of it?

var obj = {};

console.log(obj.a); // undefined
console.log(obj.why); // undefined

Why are these allowed even though a and why are never declared anywhere?

like image 374
dogant Avatar asked Oct 30 '25 03:10

dogant


1 Answers

Because object properties are not variables. The rules are different. Accessing an object property that doesn't exist gives you undefined, not an error. It's just the way the language is designed.

One possible explanation for the difference, other than just that "that's how Eich designed it," is that you don't declare object properties. You just use them. But variables must be declared (other than The Horror of Implicit Globals, and we don't have that now we have strict mode).

like image 134
T.J. Crowder Avatar answered Oct 31 '25 17:10

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!