Understanding let vs. var hoisting

C letvs. varI found out that the main difference is that let the variables are tied to the nearest block and do not rise. Also, let variables be reassigned, but cannot be redesigned within the same area. Why does this code return an "undefined" error?

let x = 10;
if (true) {
    console.log(x);
    let x = 11;
}

returns:

Uncaught ReferenceError: x is not defined(…)

Till:

let x = 10;
if (true) {
    console.log(x);
}

logs 10without errors?

+4
source share
2 answers

The main difference between varand letis as follows:

varinserted into the package function.

letclimbs onto the {}wrap block

, , x if.


:

ReferenceError -

, let , .

MDN let

ECMAScript 2015 . , , ReferenceError. " " .

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

0

let ( ). MDN:

ECMAScript 2015 .

-1

All Articles