Difference between var and let
1. Var has variable promotion, let has no variable promotion (no pre-parsing)
2. Let cannot be named twice
3. Let variables declared in the global scope are independent of window variables
4. Temporary dead zones
5. Let is constrained by block-level scope
Block-level scope comparison:
if(true) {var a=10;
}
console.log(a); / / 10
if(true) {let b=10;
}
console.log(b); //b is not defined
Copy the code
Closure writing method comparison:
Js has only two scopes: global and functional
~function () {
}()
// Now write
{
let a=10;
}
Copy the code
Looping and asynchrony problems:
// I is in the upper scope, so it is ok to print directly in the loop, but in the asynchronous execution, the loop is finished and I is assigned to 3, so 3 is printed three times
// Instead of forming a cubic variable (cubic block-level scope), I of the parent scope is assigned three times
// Add a new layer of functions
for(var i=0; i<3; i++){console.log(i); / / 0 1 2
setTimeout(() = >{
console.log(i); / / 3 3 3
},1000)}// I is in the current scope
// Each loop regenerates variable I in the block-level scope {} that is in the current scope and does not affect each other
// The loop has several block-level scopes
for(let i=0; i<3; i++){console.log(i); / / 0 1 2
setTimeout(() = >{
console.log(i); / / 0 1 2
},500)}// After es5: var loop asynchronous solution
var _loop = function _loop(i) {
console.log(i); / / 0 1 2
setTimeout(function () {
console.log(i); / / 0 1 2
}, 500);
};
for (var i = 0; i < 3; i++) {
_loop(i);
}
Copy the code
Const: The value is immutable
Any specific data value is a constant. For example, 12 is a constant
A constant cannot be reassigned
The properties of a constant reference object can be changed
Although constants cannot reference other objects, the properties of the reference object can be changed when the value of a constant is a reference data type
Cannot duplicate declaration
Block-level scopes are supported
// Define constants
const num3 =12;
num3 = 13; Uncaught TypeError: Assigjvulnerabilities to constant variable values cannot be modified
const user={
name:'aaa'
}
user.name='bb' // It can be changed without error
user={} / / an error
// The declaration cannot be repeated
const a=10;const a=10; / / an error
// Block level scope is supported
const a=10; {const a=10; / / is not an error
}
Copy the code