当前位置:网站首页>Let, const, VaR in ES6

Let, const, VaR in ES6

2022-07-19 10:05:00 qq_ forty-two million forty-two thousand one hundred and fifty-

Basic use

  • var Declare variables
  • let Instead of var, Declare variables
  • const declare constant

const Detailed explanation

const It is designed for situations where you don't want to re assign values once initialized

const Precautions for

1. Use const declare constant , Once declared , It must be initialized immediately , It cannot be left for later assignment

// Wrong writing 
const sex;
sex='male';
// Write it correctly 
const sex = 'male';

2、const Declared constant , If it is a reference data type, it is allowed to No reassignment To modify its value , But the basic data type cannot
for example

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

 Insert picture description here

let、const And var The difference between

1. Repeat statement
A variable or constant that already exists , Once again
var Allow duplicate statements ,let、const Don't allow

// Will report a mistake 
function func(a) {
    
	let a = 1;
}
func();

2. Variable Promotion
var Will raise the declaration of variables to the top of the current scope
for example

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

amount to

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

 Insert picture description here

let、const No variable promotion
for example

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

 Insert picture description here
3. Temporary dead zone
As long as... Exists within the scope let、const, The variables or constants they declare are automatically “ binding ” This area , No longer affected by external scopes
for example

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

The variables in the function have been bound in the function a, Therefore, external variables cannot be read a, So it will report a mistake
 Insert picture description here
4、 Block level scope ( The most important difference )
var There is no block-level scope

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

Variable i It's only used to control the cycle , But at the end of the cycle , It's not gone , Due to variable Promotion , Leakage becomes a global variable .
 Insert picture description here
let/const There are block-level scopes

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

i Only in for Effective in circulation
 Insert picture description here
What block level scopes are there

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

let and const Use advice

Used by default const, Only when you know that the variable value needs to be modified let

原网站

版权声明
本文为[qq_ forty-two million forty-two thousand one hundred and fifty-]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/200/202207171110015672.html