I'm a bit confused by this js behavior.
function foo(){
console.log(a)
}
foo() // ReferenceError: a is not defined
In this case everything is understandable. There is no a defined in the global scope, therefore we get the ReferenceError.
Now, this is a second example:
function foo(){
console.log(this.a)
}
foo() // undefined
So, this points to the global scope where there is no a defined. Shouldn't we get the same ReferenceError ? Why do we get undefined ?
Basically Reference error will come when you use a variable which are not declared yet, whereas undefined will come when you try to get some properties from the object and key is not present in an object, or you make a variable itself undefined
Ex.
undefined
const obj = { };
const array = [];
const newObj = undefined;
console.log(obj.id);// undefined
console.log(newObj);// undefined
console.log(array[0]);// undefined
Reference Error
const obj = { };
console.log(obj[id] = id);
Note
thisis also anobject, In your case you try to access value ofafromthis
So it's looks like
const this = {};
console.log(this.a) // undefined
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