let, const, var in ES6

Basic use

  • var declares variables
  • let replaces var to declare variables
  • const declaration constant

Detailed explanation of const

const is designed for situations where you do not want to reassign the value once it is initialized.

Things to note about const

1. Use const to declare constants. Once declared, they must be initialized immediately and cannot be left for later assignment.

//错误写法
const sex;
sex='male';
//正确写法
const sex = 'male';

2. If the constant declared by const is a reference data type, its value can be modified without reassignment
, but the basic data type cannot . For example

const person = {
    
     username: 'Alex' };
// person = {};错误
person.username = 'ZhangSan';
console.log(person);

Insert image description here

The difference between let, const and var

1. Repeated declaration.
If an existing variable or constant is declared again,
var is allowed to be declared repeatedly, but let and const are not allowed.

//会报错
function func(a) {
    
    
	let a = 1;
}
func();

2. Variable promotion
var will promote the declaration of the variable to the top of the current scope
. For example

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

Equivalent to

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

Insert image description here

There is no variable promotion for let and const.
For example

console.log(a);
let a = 1;

Insert image description here
3. Temporary dead zone
As long as let and const exist in the scope, the variables or constants declared by them will be automatically "bound" to this area and will no longer be affected by the external scope.
For example

let a = 2;
function func(){
    
    
	console.log(a);
	let a = 1;
}
func();

The variable a in the function has been bound to the function, so the external variable a cannot be read, so an error will be reported.
Insert image description here
4. Block-level scope (the most important difference)
var does not have a block-level scope.

for (var i = 0; i < 3; i++) {
    
    
	console.log('infor--'+i);
}
console.log(i);

The variable i is only used to control the loop, but it does not disappear after the loop ends. Due to the variable promotion, it is leaked into a global variable.
Insert image description here
let/const has block scope

for (let i = 0; i < 3; i++) {
    
    
	console.log('infor--'+i);
}
console.log(i);

i is only valid within a for loop.
Insert image description here
What are the block-level scopes?

  • {}
  • for(){}
  • while(){}
  • do{}while()
  • if(){}
  • switch(){}

Suggestions for using let and const

Use const by default, and use let only if you know the variable value needs to be modified.

Guess you like

Origin blog.csdn.net/qq_42042158/article/details/125828448