0

I am trying to understand both let and var keywords. It is not clear for me why do I get 'undefined' when I use let keyword?

let currentScope = 'global';
function print() {
    let currentScope = 'local';
    console.log(this.currentScope); //undefined
    console.log(currentScope);     //local
}

print();
console.log(currentScope);  //global

and here I use var

var currentScope = 'global';
function print() {
    var currentScope = 'local';
    console.log(this.currentScope); //global
    console.log(currentScope); //local
}

print();
console.log(currentScope); //global
ruleboy21
  • 5,510
  • 4
  • 17
  • 34
Tanaka
  • 316
  • 1
  • 3
  • 12
  • You shouldn't be using `this` at all here. In strict mode, the code will fail (rightfully) – Bergi May 05 '22 at 08:14
  • It comes down to what `this` is and that it does not have a `currentScope` property. – phuzi May 05 '22 at 08:15
  • 1
    Because `this` refers to `window` and using `var` it's registered on window object – Justinas May 05 '22 at 08:16
  • I did to learn because I noticed 'this' works with var, in this example? @Bergi – Tanaka May 05 '22 at 08:17
  • 2
    No, "this works with var" is not a rule you should learn. Use `globalThis.currentScope` or `window.currentScope` (inside and outside of the function), and make the connection to the global variable declaration. In fact is has nothing to do with the function at all. – Bergi May 05 '22 at 08:20

0 Answers0