In es6, The let keyword and the const keyword are provided.
The declaration method of let is the same as that of VaR. Instead of VaR, let can be used to declare the variable, so that the variable can be restricted to the current code block.
When const is used to declare a constant, its value cannot be changed once it is set.
Let allows you to declare a variable, statement, or expression that is limited to a block-level scope. Unlike the VaR keyword, the declared variables can only be global or the entire function block.
Let Syntax:
let var1 [= value1] [, var2 [= value2]] [, ..., varN [= valueN]];
The variables declared by let are only available in the declared block or sub-block. This is similar to var. The major difference between the two lies in that the scope of the variable declared by VAR is the entire closed function.
Let and VAR code example:
Function vartest () {var x = 1; if (true) {var x = 2; // the same variable! Console. log (x); // 2} console. log (x); // 2} function lettest () {Let X = 1; if (true) {Let X = 2; // different variable console. log (x); // 2} console. log (x); // 1}
Variables used when the function is not declared:
function func(){ undefined_var=110}
Before func () is called for the first time, the undefined_var variable does not exist, that is, undefined. After func () is called, undefined_var becomes a global variable.
Let keyword and const keyword