Thoroughly understand the differences between var, let, and const variables


1. var

1. Declare scope

A variable defined using var becomes a local variable of the function that contains it.

function foo(){
    
    
var msg = 'helloword'  //局部变量
}
foo()
console.log(msg)  //报错未定义 test is not defined

Here, the msg variable is defined using var inside the function. Calling function foo creates this variable and assigns a value to it. The variable msg is destroyed after the call, so an error will be reported in the final printing.

If you need to define multiple variables, you can separate each variable with a comma in one statement.

        var name = 'uzi',
            age = '22',
            team = 'rng'
        console.log(name, age, team);

As a result, Insert image description here
in strict mode, variables of evaland cannot be defined, otherwise a syntax error will be reported.arguments

2. Statement promotion

Look at the code first

      function foo(){
    
    
          console.log(name)   //undefined
          var name = 'Jay'
      }
      foo()

Why is it undefined instead of reporting an error? Because the ES runtime sees it as the equivalent code below

      function foo(){
    
    
          var name
          console.log(name)     //undefined
          name = 'Jay'
      }
      foo()

This is called variable hoisting, and variables declared using the var keyword are automatically hoisted to the top of the function scope .
In addition, it is also possible to use var to declare the same variable multiple times at once.

        function foo() {
    
    
            var name = 'Jay'
            var name = 'Eason'
            var name = 'Beyond'
            console.log(name)   //Beyond
        }
        foo()

2. let

1. Declare scope

Let and var are similar, but the very important difference is that let is block-level scope , while var's scope is function scope.

        if (1 == true) {
    
    
            var goods = 'chatgpt-3'
            let newGoods = 'chatgpt-4'
            console.log(goods);      //chatgpt-3
            console.log(newGoods);   //chatgpt-4
        }
        console.log(goods);          //chatgpt-3
        console.log(newGoods);       //报错未定义  newGoods is not defined

The reason why the newGoods variable cannot be referenced outside the if is that its scope is limited to the inside of the block.

2. Repeat the statement

let does not allow the same redundant declaration to appear in the same block-level scope, which will result in the error
Insert image description here
Uncaught SyntaxError: Identifier 'name' has already been declared
, indicating that name has already been declared.

However, the same identifier used in nesting will not cause an error because there is no duplicate declaration in the same block.

        let name = 'Macey'
        console.log(name);      //Macey
        function foo(){
    
    
            name = 'Ronaldo'
            console.log(name);  //Ronaldo
        }
        foo()

3. Variable promotion

Another important difference between let and var is that variables declared by let will not be promoted in the scope.

        console.log(name);     //undefined
        var name = 'Macey'
        console.log(age);      //未定义  Uncaught ReferenceError: Cannot access 'age' before initialization
        let age = '35'

The moment of execution before let is declared is called a " temporary dead zone ". At this stage, an error will be reported if variables declared later are referenced!

4. Global declaration

Unlike var, variables declared in the global scope using let will not become attributes of this or window objects (those declared with var will)

        var name = 'Macey'
        console.log(this.name);    //Macey
        let age = '35'
        console.log(this.age);     //undefined

However, the declaration of let still occurs globally, and the corresponding variables will persist throughout the life cycle of the page. In order to avoid repeated definition errors, it is best not to declare the same variable repeatedly.
Within a function, you can use the this keyword to refer to the global object window. Therefore, in the above code, the variable name is considered a global variable and can therefore be accessed through this or the window object.
age is visible in the block scope where it is declared, but not in the global scope. Therefore, in the global, variable b cannot be accessed through this.

5.Declaration in for loop

Iteration variables defined in a for loop using var will penetrate outside the loop body

        for (var i = 0; i < 5; i++) {
    
    
            //逻辑
        }
        console.log(i);
        for (let j = 0; j < 5; j++) {
    
    
            //逻辑
        }
        console.log(j);

Print the result Insert image description here
because the variables let iterates are limited to the inside of the block-level scope for

Let’s look at another famous example

        for (var i = 0; i < 5; i++) {
    
    
            setTimeout(() => console.log('i======', i))
        }
        for (let j = 0; j < 5; j++) {
    
    
            setTimeout(() => console.log('j======', j))
        } 

The reason for printing the result Insert image description here
is that the value saved in var when exiting the loop is: 5. When setTimeout is executed later, all i are the same variable, so the output is the same value.
When using let iteration declaration, JS will declare a new iteration variable for each iteration loop. Each setTimeout refers to a different variable instance.
This behavior of declaring an independent variable instance for each iteration applies to all styles of for loops, including for-in and for-of loops.

3. const

The behavior of const is basically the same as let. The only important difference is that it must assign a value when declaring a variable . Once a simple data type (numeric value, string, Boolean value) is declared, it cannot be modified or an error will be reported.

        const name
        //一旦声明了就必须赋值 Missing initializer in const declaration
        const age = '22'
        age = '23'              //不能赋值   Assignment to constant variable

        const color = 'red'
        const color = 'blue'    //不能重复声明 Identifier 'color' has already been declared

        const name = 'Macey'
        console.log(name);      //Macey  
        function foo() {
    
    
            const name = 'Ronaldo'
            console.log(name);  //Ronaldo   声明的作用域也是块级
        }
        foo()

The restrictions of a const declaration apply only to references to the variables it points to. If const refers to an object or array, then modified internal properties are allowed.

      const person = {
    
    
          name: 'Jay'
      }
      person.name = 'Eason'
      console.log(person.name);      //Eason

If you really want to freeze the object, you should use Object.freezethe method.

        const person = Object.freeze({
    
    
            name: 'Jay'
        })
        // 常规模式时,下面一行不起作用;
        // 严格模式时,该行会报错
        person.name = 'Eason'
        console.log(person.name);       // Jay

end:

Declaration style : With let and const, var is no longer used, because variables have clear scope, declarations prevail, and immutable values.
The priority of const should be higher than let : using const declaration can force the browser to keep variables unchanged when running, and can also allow static code analysis tools to detect illegal assignment operations in advance. Only use let when you know in advance that a variable will be modified in the future. This allows you to infer that the values ​​of certain variables never change, and also allows you to quickly detect unexpected behavior caused by accidental assignments.

Reference: Advanced Programming with JavaScript (4th Edition)

Guess you like

Origin blog.csdn.net/Jet_Lover/article/details/129750043