To put it simply: let is a bugthat fixes the scope of var and becomes more useful. Let is the better var. var is scoped to a variable defined by var at the scope of the function, scoped to a function body, not the curly braces {} that we understand in other languages. inside. and let is the block level (the content enclosed in curly 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.
var a = [];
for (Let i = 0; i < i++) {
A[i] = function () {
Console.log (i);
};
}
A[6] (); 6
Console.log (A[6]); function () {Console.log (i)}
Since the loop ends, each item of array A is function () {Console.log (i)}, then the a[6] () output is 6 How did it come true? has the Let saved ten states?
this is because The JavaScript engine internally remembers the value of the last loop, and when it initializes the variable I of this round, it is calculated on the basis of the previous cycle.
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 declared by the Var command and is valid at global scope, so there is only one variable i globally . Each cycle, the value of the variable i is changed, and within the loop is assigned to the inside of the function of the array a console.log (i), the inside of the I point is the global I. That is, all of the members of the array a, I, point to the same I, resulting in the runtime output is the last round of the value of I , that is, ten.
that is, after the loop ends, each item of array A is function () {Console.log (i)}. Before executing the a[6] function, the value of I now is already ten .
What is the difference between Var, let, and const in JavaScript?