0

I am trying to figure out the difference between undefined and not defined. So below is one simple program.

var name = 'John';
var age = 30;

var obj = {
    //name: 'Joe',
    age: 29,
    getInnerName: function() {
        return this.name;
    },
    getOuterName: () => {
        return this.name;
    }
}

console.log(obj.getInnerName()); //undefined
console.log(obj.getOuterName()); John

My doubt is, why first console.log writes undefined and not the error -> Uncaught ReferenceError: name is not defined?

Explanation is appreciated!

PS - Please correct the question If I fail to convey What I meant.

1 Answers1

1

To clarify, that error : Uncaught ReferenceError: name is not defined occurs when you use a variable that is not defined, example:

test === 'test'
VM948:1 Uncaught ReferenceError: test is not defined
    at <anonymous>:1:1

but when you use this.name, it won't cause that error, because it's not a variable, it's a property of this, so you get undefined in return, or the value of that property if it exists

in your particular case, since this === window, name and this.name will give the same result, but that's not always the case

However trying to use that property for example like that :

this.doesNotExist.toString()
VM1202:1 Uncaught TypeError: Cannot read properties of undefined (reading 'toString')
    at <anonymous>:1:19

will cause an error

also you need to understand the differences between arrow functions and normal functions, look a this answer : https://stackoverflow.com/a/34361380/8126784

Lk77
  • 2,203
  • 1
  • 10
  • 15
  • Thanks @LK7. "but when you use this.name, it won't cause that error, because it's not a variable, it's a property of this, so you get undefined in return" This line helped me understand why it did not throw any error. – Sanket Karandikar May 23 '22 at 09:07