javascriptvararrow-functionsletglobal-scope

How can we explain the differences between let and var in global scope of browser?


The result is 10 when I use var keyword:

var x = 10;
let foo = {
  x: 90,
  getX: () => {
    return this.x
  }
}

console.log(foo.getX())

But undefined is the result when I use let keyword:

let x = 10;
let foo = {
  x: 90,
  getX: () => {
    return this.x
  }
}

console.log(foo.getX())

I cannot understand why there are two different results, when both of them have the same global scope.


Solution

  • As your object method, you used an arrow function, whose context (this value) is bound to the function in which you've declared them.

    That is, your getX function's this value will be the global object (window).

    Then you try to access the x property of that object, which is 10 (as global-scope var creates properties on the global object) in case of var.

    However, let never creates a property on the global object, therefore in your second example, you get undefined.

    Try it:

    const object = {
      method: () => this
    }
    
    console.log(object.method() === window) //true
    
    var foo = 1
    let bar = 2
    
    console.log(foo, window.foo) // 1 1
    console.log(bar, window.bar) // 2 undefined