The difference between var, let and const? (ES6-interview questions)

1. What is the difference between var, let, and const?

Difference one:

        var does not have block-level scope, while let and const have block-level scope.

        Solved two problems in es5:

                                              1. Inner variables may override outer variables

                                              2. The loop variable used for counting is leaked as a global variable

        example:

<script>
        function fn(){
            for(var i = 0; i < 3; i++){
                console.log(i)   //本来这个循环后在控制台输出0 1 2
            }
            console.log(i)    //但是,因为var声明的变量没有块级作用域,所以这里还可以输出3
        }
        fn();  //调用函数
</script>

        The output of the above code is as follows:

         Note: block scope is enclosed by {}.

Difference two:

        There is variable promotion for var, but there is no variable promotion for let and const, that is, variables can only be used after declaration, otherwise an error will be reported.

        example:

        

//var存在变量提升,let和const不存在变量提升,即变量只能在声明之后使用,否则会报错。
        console.log(a)
        var a = 1128

        The output is as follows:

        No error was reported, but the value of 1128 was not obtained either. So var exists variable hoisting.

        How to understand? (As shown below)

        

 Difference three:

        When var declares a variable, the variable can be declared repeatedly, and the variable declared later with the same name will overwrite the previously declared variable.

        const and let do not allow repeated declaration of variables.

        example:

         

 

Difference four:

        var and let declare variables, and const declares constants.

        Variables declared by var and let can be assigned again, but const cannot be assigned again.

        example:

 

Guess you like

Origin blog.csdn.net/weixin_54614831/article/details/126433054