Why when I try to access a variable that don’t exist, javascript throw an exception but when I try to access a property that don’t exist in an object, javascript returns an undefined value?
For example, this case returns an undefined value:
function Foo(){
console.log(this.bar);
}
Foo();
But, in this other example, javascript throw an exception:
function Foo(){
console.log(bar);
}
Foo();
ReferenceError: bar is not defined
As every object in JavaScript is a dictionary, also known as map in other languages,
this.baris equivalent tothis['bar'], i.e. access to a value by a key. In most languages, e.g. in Java, returningnull,NULL, orundefinedallows you to conditionally create this slot if it does not exist yet, without dealing with exceptions or any other side effects.However, when you just write
console.log(bar)without specifying a context for thebar, it would be impossible to create a reasonable pattern where returningundefinedwould have a semantic meaning. There are multiple contexts, some of them dynamic, like global contextwindowin the browser, where thebarmight be defined during the runtime, so it cannot be a compile time error (as opposed to Java or C++). Hence runtime exception is thrown when variable name cannot be resolved.