Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A question about let when it acts as a global variable in ES6 [duplicate]

As shown in the code below, I used var value = 1, and the value obtained is 1 . I can understand this because return this.value here the this points to the window, so I can print out the global variable value.

var value = 1;
let obj = {
  getValue: function() {
    return function() {
      return this.value;
    }
  }
}
console.log(obj.getValue()());  // 1

But if I use let to declare the value, I can't get the value of the value, the print is undefined. This is very puzzled, whether it is using let, or var statement, value is a global variable. Why is there such a difference?

let value = 1;
let obj = {
  getValue: function() {
    return function() {
      return this.value;
    }
  }
}
console.log(obj.getValue()());  // undefined

Do you know why? Can you tell me? Thank you very much.

like image 723
DangoSky Avatar asked Sep 16 '25 16:09

DangoSky


2 Answers

At the top level of programs and functions, let, unlike var, does not create a property on the global object. For example: Scopping rules MDN

var x = 'global';
let y = 'global';
console.log(this.x); // "global"
console.log(this.y); // undefined
like image 168
Code Maniac Avatar answered Sep 19 '25 06:09

Code Maniac


As MDN explains:

At the top level of programs and functions, let, unlike var, does not create a property on the global object.

This is because let always creates a lexically scoped variable. If it were to create properties of a global object instead, those properties would be visible to code in other scopes. They wouldn't be lexically scoped anymore, defeating the point of using let.

If you're wondering how there can be "other scopes" not lexically contained within the global scope, there can be multiple script files. Or look at this variation of your example:

let getValue = function() {
  return this.value;
};

let value = 1;
console.log(getValue());

Using var value = 1; this would still output 1. But with let it outputs undefined because the function is defined lexically outside the block in which value was declared, so it can't access it, even by going through the global object.

Or as MDN puts it:

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used.

That's let's purpose for which it was designed.

like image 30
melpomene Avatar answered Sep 19 '25 07:09

melpomene