Differences between JavaScript ES6 var let const and its usage

Time:2021-2-19

In ES6, two variable naming methods are updated
let const
In short:
let: comparative var cannot be defined repeatedly, but has scope {self closure problem}
It is often reflected in if judgment and for loop
const: cannot be defined repeatedly. It will be directly defined as a constant
example

function fun(){
var a=1
var a=2
}
fun()
Alert (a) // 2 will pop up here

Why are the variables defined in the function still accessible outside the function?
Because of the above, there is no scope problem, and it can be repeatedly defined
In the same way, let has no mistakes. Let can replace VaR in 99% of daily situations

function fun(){
let a=1
let a=2
}
fun()
alert(a)
//An error will be reported directly here. Even if the second definition is deleted, "undefined" will pop up. This is because of the scope problem of let. The problem defined in the function can only be used in the function

As for the const constant, he can use it as he likes, but he can’t use it