The difference between var, let and const in JavaScripct

In ES5, there are only two forms of variable declaration: var and function. But because the variable declared by var has certain disadvantages, ES6 proposes the use of let and const to declare variables. Let's take a look at the difference between them.

1. Is there variable promotion?

The variable declared by var has variable promotion (the variable is promoted to the top of the current scope). That is, the variable can be called before the declaration, and the value is undefined.

Variable promotion does not exist for let and const. That is, the variables declared by them must be used after declaration, otherwise ReferenceError will be reported.

console.log(f) //undefined
var f = 1 ;

console.log(g) //ReferenceError: g is not defined
let g = 2;

console.log(h) //ReferenceError: g is not defined
const h = 2;

2. Is there a temporary dead zone?

Let and const have a temporary dead zone. That is, as long as there is a let command in the block-level scope, the variables declared by it are "bound" to this area and are no longer affected by external influences.

var tmp = 123;
if (true) {
    
    
  tmp = 'abc'; // ReferenceError
  let tmp;
}
//以上代码if后面{
    
    }形成了块级作用域,由于使用let声明了tmp,则这个变量就绑定了块区域,在声明之前使用,会报错。

在代码块内,使用let命令声明变量之前,该变量都是不可用的。This is grammatically called "temporal dead zone" (TDZ for short).
In short, the essence of the temporary dead zone is that as soon as it enters the current scope, the variable to be used already exists, but it is not available. Only when the line of code that declares the variable appears, can the variable be obtained and used.

3. Is it allowed to declare variables repeatedly?

var allows repeated declaration of variables.
Let and const are not allowed to declare variables repeatedly in the same scope.

var f = 4;
var f = 5;
console.log(5) //5

let g = 6;
let g = 7;
console.log(7) //SyntaxError: Identifier 'g' has already been declared

const h = 8;
const h = 9;
console.log(h) //SyntaxError: Identifier 'g' has already been declared

4. Is there a block-level scope?

There is no block-level scope for var.
Let and const have block-level scope.

What is block-level scope:

The scopes in ES5 are: global scope and function scope. There is no concept of block scope. Therefore, there are also a series of problems.

5. Can the declared variables be modified?

Var and let are fine.
const declares a read-only constant. Once declared, the value of the constant cannot be changed. The variable declared by const must not change the value, which means that once const declares the variable, it must be initialized immediately and cannot be left for later assignment.

Guess you like

Origin blog.csdn.net/zxlong020/article/details/108435749