Detailed explanation of the difference between var, let and const

  let and const are new features introduced by ECMAScript6, let is a "standard" that can replace var, so we discuss the difference between var, let and const, first of all, we should know what is not standardized in var, or what are the disadvantages .

Characteristics of var

Variable promotion

  var is a keyword used by Javascript to define variables, this is a simple variable definition method

var a = 0;

  But if we query this a before defining this variable, we will not report an error

console.log(a); // undefined
var a = 0;
console.log(a); // 0

  Although it outputs undefined, this is not what we want. We hope that the variable cannot be accessed before the variable is initialized. Although this is a constraint, it can make your program more elusive and maintainable. The var has been able to var a = 0;be accessed before, because this sentence is actually carried out in the following order at compile time:

var a;
console.log(a); // undefined
a = 0;
console.log(a); // 0

  This is why the second line a will print out undefined. This is called variable promotion. When using var to initialize a variable, at the beginning of the scope, the variable will be defined first, and then assigned (initialized) later. So even you can play like this:

console.log(a); // undefined
a = 0;
console.log(a); // 0
var a;

  This can also be successfully printed, so everyone should understand that var will trouble the maintenance of the program's eyes? a Obviously what I didn't see after looking down all the way, is it still used normally? ! ! At this time, you need to check whether there is hidden in the scope from the scope. var a;If not, you need to look outside the scope.

console.log(a); // undefined
let a = 0;
console.log(a); // 0
var scope

  Let's look at the following code again

for(var i = 0; i < 5; i++){
    var a = 0;
}
console.log(i); // 5
console.log(a); // 0

  The variables i and a we defined in the for loop block can be taken outside the loop, which is obviously not standardized.

  Then here can give you another question that is often mentioned in the interview

for (var i = 0; i < 5; i++) {
    setTimeout(function () {
        console.log(i); // 5 5 5 5 5 
    }, 300);
}
for (let j = 0; j < 5; j++) {
    setTimeout(function () {
        console.log(j); // 0 1 2 3 4
    }, 300);
}

  The code is almost the same, because of the difference in the scope of var and let, the results obtained are very different. For the first for loop, i is valid in the global scope, and the definition of i is not found in the setTimeout function, so the variable i can be found globally. After the for loop is executed, in the event loop, in setTimeout 'S anonymous function starts to execute. At this time, the global i is actually already 5, so all print out 5.
  For the second for loop, let has the concept of block-level scope, and it is worth noting that the let statement at the head of the for loop has a special behavior. This behavior indicates that the variable is declared more than once during the loop. Each iteration will be declared. Each subsequent iteration will initialize the variable with the value at the end of the previous iteration. This makes our j, each execution is actually a different variable in the block scope, naturally it is not the final 5.
  So if you can't use E6, you can use closures to create a new scope. This closure can retain a reference to the scope in which it is declared, forcing i to remain in the scope of the self-executing function so that it is not recycled. In this way, each time i value can be obtained.

for (var i = 0; i < 5; i++) {
    (function (i) {
        setTimeout(function () {
            console.log(i) // 0 1 2 3 4
        }, 300)
    })(i)
}
var can be defined repeatedly

  This is easy to understand. Var is allowed to be defined twice without reporting errors.

var a = 0;
console.log(a); // 0
var a = 1;
console.log(a); // 1

  The editor will ignore the var keyword when judging that there are already declared variables of the same name, and then directly assign a value, so if a repeated statement has an initial value, then it is an assignment statement. If a statement that is reused does not have an initial value, then it will not have any effect on the originally existing variables. This is legal for JS before ES5, but after ES6, it is considered unscientific to repeat this definition. Let and const do not allow a variable with the same name to be repeated in the scope.

Now let's talk about let

Temporary dead zone

  First of all, it is absolutely not allowed to use this variable before let defines the variable

console.log(a); // ReferenceError: a is not defined
let a = 0;
console.log(a); // 0

  The let statement will not be promoted to the top of the current execution context. From the block-level scope to the initialization position, it is called "temporary dead zone", so using a in the temporary dead zone for a will report a Reference error. .

Block scope

  The variable declared by let has a block-level scope, and the variable cannot be accessed outside the block-level scope, and var is different. The variables defined in the for loop can be accessed externally, which can cause some unexpected bugs. Note that the curly braces {} are block-level scope, not to say function scope.

No redefinition
let a = 0;
console.log(a); // 0
let a = 1;
console.log(a); // SyntaxError: Identifier 'a' has already been declared
window object

  In HTML, the global scope is for the window object. The global scope variable defined by the var keyword belongs to the window object, while let defines not. Note that this is in a browser environment, if it is Node, there is no window object.

var a = 0;
console.log(window.a) // 0
let b = 1;
console.log(window.b) // undefined

const

  In fact, const is very very similar to let. Let has the same characteristics as let, and const has it. The difference is that first, const does not allow "modification" of variables. Second, const must be initialized, and let does not need to.

const a = 0;
a = 1; // TypeError: Assignment to constant variable
const b; // SyntaxError: Missing initializer in const declaration

  However, what const defines is not a constant in the true sense. If you define an object or an array, it can actually be changed, but you cannot assign different data types to him. Generally, you can remember: after const is initialized, you cannot use = Assignment.

const a = {}
a.b = 1;
console.log(a) // { b: 1 }
a = 1 // TypeError: Assignment to constant variable

Guess you like

Origin www.cnblogs.com/JobsOfferings/p/varLetConst.html