Declaring variable with let [duplicate]

0

In the following code, why is not João returned when trying this.pessoa ? Where let was declared should go global, or not?

let pessoa = 'João'
console.log(this.pessoa) //undefined
    
asked by anonymous 27.11.2018 / 12:23

1 answer

1

Exactly the opposite, let leaves local, moreover, has block scope, is more restricted than var . var still has this problem of not considering the entire scope. this has no such specific scope.

If you can ensure that your code will run in new browsers, or you can run a transpiler before it matches version only let should be used (any use of var or without it should be considered gambiarra).

See that there is difference in each form of declare and whether it accesses by this or not.

let x = 'João';
var y = 'João';
z = 'João';
console.log(this.x);
console.log(this.y);
console.log(this.z);
console.log(x);
console.log(y);
console.log(z);

See more in What is the difference between declaring variables using let and var? and also What is the context and how does Javascript work? .

    
27.11.2018 / 12:32