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?
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).
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