Let is a bug that fixes the scope of Var and becomes more useful. Let is the better var. The function of Var is then applied, and let is the block level (the content enclosed in braces)
Const declared variables can only be assigned at the time of declaration, not arbitrarily modified, this is the biggest feature.
A variable declared with Var, whose scope is within the function where the statement is located, and there is a variable elevation phenomenon;
Use a let declaration of a variable whose scope is within the code block where the statement resides, and there is no variable elevation;
A constant is declared with const, and the value of the constant cannot be modified in the code that appears later.
variables defined by 1.const cannot be modified and must be initialized .
12345 |
const b = 2; //正确 // const b;//错误,必须初始化 console.log( ‘函数外const定义b:‘ + b); //有输出值 // b = 5; // console.log(‘函数外修改const定义b:‘ + b);//无法输出 |
2.var defined variables can be modified, if not initialized will output undefined, will not error.
123456789 |
var a = 1; //var a;//will not error console.log ( + A ); //can output a=1 function change () { a = 4; console.log ( + A ); //can output a=4 } change (); console.log ( "function call after Var definition a for function internal modified value: ' + a); //can output a=4 |
3.let is a block-level scope, and after the function is defined with let, there is no effect on the outside of the function.
12345678 |
let c = 3; console.log( ‘函数外let定义c:‘ + c); //输出c=3 function change(){ let c = 6; console.log( ‘函数内let定义c:‘ + c); //输出c=6 } change(); console.log( ‘函数调用后let定义c不受函数内部定义影响:‘ + c); //输出c=3 |
Analysis of the Const, VAR, and let differences in JavaScript