Es6 block-level scope

es6 block-level scope let

Why not add the sentence "let a = 2000" in the following code, the console.log (a) result is 100; and why you report an error an after adding this sentence is the definition.
I came across the knowledge of let in es6.

var a = 100, b = 10;
function fun(){
    if(true){
        console.log(a);
        let a = 2000;
    }
}
fun();// 

if var a = 200 is included in if, then the result of console.log (a) is why the program reported an error here after undefined, was changed to let?

Apr.19,2021
There is a variable improvement in the use of

var, that is, when a variable is used, it is found in the scope. So in console.log (a), when looking for var a globally, after promotion, it is equivalent to var a; console.log (a);
let and const will not be promoted, that is, in console.log (a), let a comes after, which means that a has not yet been defined, so it is seen before undefined
https://codeshelper.com/a/11.
. You can take a look at the use of ES6.


because you use var , you will have a variable that promotes var hoisting , so you won't report an error.
Source code

function fun() {
  if (true) {
    console.log(a);
    var a = 2000;
  }
}

variable is equal to this after promotion

function fun() {
  var a;
  if (true) {
    console.log(a);
    a = 2000;
  }
}

there is no such concept in let. Of course, if you quote an undefined variable, you will make a mistake.


temporary dead zone learn


there is no let output outside the global variable var a = 100

there is a temporary dead zone with let until let a = 2000; an is not defined

changing let to var, has a variable improvement, which is equivalent to the following code


1.<br>2.if,<br>3.varjs<strong></strong>

a:
    :a > undefined 
    :a -> 100 
fun :a -> undefined (var)
fun -> console.log(a) -> undefined
              :a -> 2000 
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3e4ab-2c3e4.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3e4ab-2c3e4.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?