There are three ways to declare variables in javascript: VAR, let, and Const.
The 1.const declaration creates a read-only constant. This does not mean that the value that the constant points to is immutable, but that the value of the variable identifier can only be assigned once and must be initialized.
const b = 2;
//正确
// const b;//错误,必须初始化
console.log(
‘函数外const定义b:‘
+ b);
//有输出值
// b = 5;
// console.log(‘函数外修改const定义b:‘ + b);//无法输出
The 2.var statement is used to declare variables. var A;//undefined (if not initialized, output undefined)
var a=666; //放到方法外面为全局变量
function Fun () {//var a=555; Put inside the method as a local variable, can only read Console.log (a) inside the fun (); 666} If the var keyword is not practical, the Var will affect the scope of the variable, regardless of whether it is placed in the method or outside the method.
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. ES6 has added
let
Command used to declare a variable. Its usage is similar to
var
, but the variables that are declared are only
let
Valid within the code block where the command resides. A local variable is declared. Take the For loop as an example: The following code if you use the
var
, and the final output is
10
。
var a = [];for (var i = 0; i < ten; i++) { A[i] = function () { console.log (i); };} A[6] (); 10
In the above code, the variable i
is var
declared and is valid at the global scope. So each time the loop, the new i
value overwrites the old value, resulting in the final output of the last round of the value i
. (common in closure studies)
If used let
, the declared variable is valid only within the block-level scope, and the last output is 6.
var a = [];for (Let i = 0; i < ten; i++) { A[i] = function () { console.log (i); };} A[6] (); 6
In the above code, the variable i
is let
declared, the current is i
only valid in this round loop, so each loop i
is actually a new variable, so the final output is 6
.
The const, VAR, and let differences in JS