Declaring variable with Let

Asked

Viewed 125 times

0

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

let pessoa = 'João'
console.log(this.pessoa) //undefined
  • 4
  • And if you’re defining pessoa, why did you use the this?

  • I just started and my difficulty is being no this. As in this case this represents the global scope and Let was created globally, I went to confirm with this. I saw an example of this once, but in the example returned correct the name, already in my gives Undefined.

  • @Jonatas Did the answer solve your question? Do you think you can accept it? See the [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

1

Just the opposite, the let leaves local, further, has block scope, is more restricted than var. The var still has this problem of not considering the whole scope. The this has no such specific scope.

If you can guarantee that your code will run on new browsers, or you can run a transpilator before compatibilize version only the let should be used (any use of var or without it should be considered gambiarra).

Note that there is difference in each way declare and access 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);

I put in the Github for future reference.

See more in What is the difference between variable declaration using Let and var? and also What is and how the context works in Javascript?.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.