0
let a=5;
var b=6;

console.log(this.a); //why we get undefined if we run this in global context.
console.log(this.b); //output:6

let a=5; why we get undefined if we console.log(this.a);

Sanket Shah
  • 2,888
  • 1
  • 11
  • 22
  • 2
    [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let): _"At the top level of programs and functions, **`let`**, unlike `var`, **does not create a property on the global object**"_ – Andreas Sep 23 '21 at 10:35
  • 1
    Unlike `let`, variable with `var` is added on the global window object. – Yousaf Sep 23 '21 at 10:35
  • The [documentation for `let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) explains the differences. – Andy Sep 23 '21 at 10:37

1 Answers1

1

From MDN Web Docs:

"unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope. The other difference between var and let is that the latter is initialized to a value only when a parser evaluates it"

Can read more about it here: MDN - let

Yousaf
  • 27,861
  • 6
  • 44
  • 69
Ran Turner
  • 14,906
  • 5
  • 47
  • 53