Go to front end vue.js learning notes – 1.2 – use let and const to define constant variables

Time:2021-6-12

Define variable constants

let

Let defines constants

const

Const defines variables

Why not use VaR

The simplest answer is that let provides block scoping, which is more refined than VaR’s function scoped control.

Here is an example:

Question: in the following example, please say the print result of the console.

var callbacks = [];
(function() {
for (var i = 0; i < 5; i++) {
callbacks.push( function() { return i; } );
}
})();
console.log(callbacks.map( function(cb) { return cb(); } ));

We execute the for loop five times, pushing a function to thecallbacksArray. lastcallbacksThe execution result of each function in the array is printed out.
A novice Engineer may answer after careful consideration[0, 1 , 2, 3, 4]And then it fell inJavaScript“Hoisting trap”.

Only when you understand hoisting can you give the right answer[5, 5, 5, 5, 5]

var callbacks = [];
(function() {
var i;
for (i = 0; i < 5; i++) {
callbacks.push( function() { return i; } );
}
})();
console.log(callbacks.map( function(cb) { return cb(); } ));

Notice the code above,JavaScriptRaise the variable to the top of the function definition, through the entireforCirculation,callbacksThe five functions stored inside point to the same variableiThe value of is already 5. So the final printed value is 5.

In the past to solve this problem through a variety of strange sex skills, and successfully return[0, 1, 2, 3, 4]Now we have itletIt’s easy to solve the problem:

var callbacks = [];
(function() {
for (let i = 0; i < 5; i++) {
callbacks.push( function() { return i; } );
}
})();
console.log(callbacks.map( function(cb) { return cb(); } ));

becauseletHas a block scope, so useletDeclared variablesiWill not be promoted to the top of the function,iThe scope of isforLoop, there will be a separate value for each loop.

Should we not use itvarWhat happened? If you want a variable to have a function scope,varIt’s still very useful.

This work adoptsCC agreementReprint must indicate the author and the link of this article

Thank you for your attention