[JavaScript]: Understand var let const

Var
let
const
declaration style and best practices

variable

ECMAScript variables are loosely typed, which means that variables can be used to store any type of data. Each variable is nothing but a named placeholder for storing arbitrary values. There are three keywords to declare variables: var, let, const. Among them, var can be used in all versions of ECMAScript, while let and const can only be used in ECMAScript6.

1.var

```javascript var message ``` declares a variable named message, which can be used to store any type of value (without initialization, the variable will store a special value undefind)
var message="hi";
message=100;//合法但不推荐

Although it is not recommended to change the type of the saved value of the saved variable, it is completely valid in ECMAScript.

1.var scope

The variable defined by the var operator becomes the local variable of the function containing it

 function test() {
    
    
 var message="hi";
}
console.log(message);//出错

Here the message variable is defined by var inside the function, which means that the variable will be destroyed when the function exits, so printing the message will report an error

2. Var statement promotion

The following code will not report an error when using var. Because variables declared with var are automatically promoted to the top of the function scope:

function foo () {
    
    
console.log(age);
var age=20;
}
foo();

//类似于

function foo () {
    
    
var age;
console.log(age);
var age=20;
}
foo();//undefined

This is the so-called "promotion", that is, pulling all variable declarations to the top of the function scope. In addition, it is no problem to use var repeatedly.

function foo() {
    
    
var age = 16;
var age = 26;
var age = 36;
}

2.let

Let is similar to var, but has a very important difference. The most obvious difference is let: the declaration scope is the block var: the declaration scope is the function
if(true) {
    
    
var age= 26;
console.log(age);//26
}
console.log(age);//26

if(true) {
    
    
let age= 26;
console.log(age);
}
console.log(age);//ReferenceError: age 没有定义

Here, the age variable cannot be referenced outside the if block because its scope is limited to the inside of the block.
1) Block scope is a subset of function scope, so the scope restrictions that apply to var also apply to let
2) Let does not allow redundant declarations in the same block scope, which will lead to

Cause an error

var name;
var name;

let age;
let age;//SyntaxError:标识符age已经声明过

1. Temporary dead zone

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

//name会被提升
console.log(name);//undefined
var name ="Matt";

//age不会被提升
console.log(age);//ReferenceError: age 没有定义
let age=26;

When parsing the code, the JavaScript engine will also pay attention to the let declarations that appear after the block, but before that, you cannot refer to undeclared variables in any way. The moment of execution before let declaration is called "temporary dead zone", at this stage referencing any variable declared later will throw a ReferenceError.

2. Global declaration

Unlike the var keyword, variables declared in the global scope using let will not become properties of the window object (variables declared by var will)

var name ="xiao";
cosole.log(window.name);//"xiao"

let age= 20;
console.log(window.age);//undefined

However, let declarations still occur in the global scope, and the corresponding variables will continue in the life cycle of the page. Therefore, in order to avoid SyntaxError, you must ensure that the page does not declare the same variable repeatedly.

3. Condition description

When using var to declare variables, because the declaration will be promoted, the JavaScript engine will automatically merge the redundant declarations into one declaration at the top of the scope. Because the scope of let is a block, it is impossible to check whether a variable with the same name has been previously declared using let, and it is also impossible to declare it without a declaration.

<script>
var name= "Continue"
let age=20
</script>

<script>
//假设脚本不确定页面中是否已经声明了同名名量
//那它可以假设还没有声明过

var name ="Continue"
//这里没问题,因为可以被作为一个提升声明来处理
//不需要检查之前是否声明过同名变量

let age=20;
//如果age之前声明过,这里会报错
</script>

4. Let statement in the for loop

Before let appears, the iteration variable defined by the for loop will penetrate outside the loop body:

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

After changing to let, this problem disappeared, because the scope of the iteration variable is limited to the inside of the for loop block:

for(let i=0;i<5;++i){
    
    
}
console.log(i);//ReferrenceError:i 没有定义

When using var, the most common problem is the peculiar declaration and modification of iteration variables:

for(var i = 0; i< 5; ++i){
    
    
  setTimeout(()=>console.log(i), 0)
}
//实际上输出5、5、5、5、5

This happens because when you exit the loop, the iteration variable holds the value that caused the loop to exit: 5. When the timeout logic is executed later, all i are the same variable, so the output is the same final value.
When using let to declare iteration variables, the JavaScript engine will declare a new iteration variable for each iteration loop in the background. Each setTimeout refers to a different variable instance.

for(let i = 0; i< 5; ++i){
    
    
  setTimeout(()=>console.log(i), 0)
}
//实际上输出0、1、2、3、4

3.const

The behavior of const is basically the same as that of let. The only important difference is that the variable must be initialized at the same time when it is used to declare the variable, and trying to modify the variable declared by const will cause a runtime error
const age=20;
age=22;//TypeError:给常量赋值

//const也不允许重复声明
const name="Continue";
const name="xiao"//SyntaxError

//const声明的作用域也是块
const name="Continue"
if(true){
    
    
const name="xiao"
}
console.log(name);//Continue

The restriction of const declaration only applies to the reference of the variable it points to. In other words, if the const variable refers to an object, then modifying the internal properties of this object does not violate the restrictions of const.

const person(){
    
    };
person.name="Continue";

Even though the JavaScript engine will create independent variable instances for the let declaration in the for loop, and const variables are very similar to let variables, you cannot use const to declare iteration variables (because the iteration variable will increment):

for(const i = 0; i< 5; ++i){
    
    
}//TypeError:给常量赋值

4. Statement style and best practices

1. Don't use var

With let and const, most developers will find that var is no longer needed. Restricting yourself to only use let and const helps to improve code quality, because variables have a clear scope, declaration position, and constant value.

2. const first, let second

Using the const declaration can force the browser to keep the quality unchanged during runtime, and it can also allow static code analysis tools to detect illegal assignment operations in advance. Therefore, many developers think that const should be used first to declare variables, and only use let when they know in advance that there will be changes in the future. This allows developers to more confidently judge that the value of certain variables will never change, and at the same time quickly discover unexpected behaviors caused by accidental assignments.

Guess you like

Origin blog.csdn.net/qq_43522998/article/details/112800564