Why reading undeclared variable gives reference error but undeclared object property returns undefined in javascript?

In below code, if I print this.property2 on console, JS engine prints undefined, if I replace the statement to print only property2 compiler
throws a reference error
if I declare the variable property2 then the compiler will return undefined.

function foo() {
  var property;
  console.log(this.property2)
  console.log(this.property2 === property2)
  console.log(property2)
}

foo.property="property value";
var property2; // modified to resolve reference error
foo();
console.log(foo.property);

As I have shown in the code this.property2 is equal to property2 so why javascript behaves differently for the same variable.

Coming to my question are both variables different? (this.property2 and property2) if they are different why the comparison returns true?
and if they are not different then why I have to declare property2 to get the return value and this.property2 returns values without
declaration.

am I missing anything?


Source: stackoverflow-javascript

Leave a Reply

Your email address will not be published. Required fields are marked *