Problem with let keyword

I played with some code and came across a situation where I could not determine why the “let” behaves the way it does.

For the bottom block of code:

var x = 20; // global scope function f() { let x = x || 30; } f(); // VM3426:1 Uncaught ReferenceError: x is not defined(…) 

I get the error "x not defined" when I execute f (). I understand that the "let" variables were not raised, but since "x" has a global copy, why not the line inside the "f" function by default for the global copy, and not to throw an error? "Allows" to set the variable to uneclared (instead of "undefined" with var due to the rise) at the beginning of the function? Is there a way to get a global copy of "x" inside a function?

+5
source share
4 answers

The exception is the right side of x - when you initialize the variable block-scope x , the global one is already “forgotten”, but the new one is not yet declared and cannot be used during initialization

Comparison with an explicit call to global one

  function f() { let x = window.x || 30; } 

Also take a look at this MDN article on dead zones

+5
source

let lets you declare variables that are limited in scope to the block, statement, or expression on which it is used. This is not like the var keyword, which defines a variable globally or locally for an entire function regardless of block area.

Here in your case an exception is thrown, because you define let with the same name.

Additional Information

0
source

Declaring a local x overshadows the global one, and a new one has not yet been declared first and cannot be used during initialization. This is the same situation as the following:

  var foo = 5; function do_something() { console.log(foo); // ReferenceError let foo = 2; } do_something(); 

For reference MDN

As suggested by @ m.antkowicz, you can use window.x in your case.

0
source

you can use this keyword to access the global area

 var x= 20; // global scope function f() { let x =this.x || 30; } f(); 

but in strict mode it will be undefined by default

Read https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this

0
source

Source: https://habr.com/ru/post/1259536/


All Articles