The difference between var and let, const and code summary

1. Will the declared variable be mounted on the window?

Variables declared by var will be mounted on the window, while variables declared by let and const will not

code show as below:

var a = 100;
console.log(a,window.a);    // 100 100

let b = 10;
console.log(b,window.b);    // 10 undefined

const c = 1;
console.log(c,window.c);    // 1 undefined

2. Is there variable promotion?

Var declared variables have variable promotion, let and const do not have variable promotion

code show as below:

console.log(a); // undefined  ===>  a已声明还没赋值,默认得到undefined值
var a = 100;

console.log(b); // 报错:b is not defined  ===> 找不到b这个变量
let b = 10;

console.log(c); // 报错:c is not defined  ===> 找不到c这个变量
const c = 10;

3. Is there a block-level scope?

let and const declarations form block scope, var declarations do not have block scope

code show as below:

if(1){
    
    
    var a = 100;
    let b = 10;
}

console.log(a); // 100
console.log(b)  // 报错:b is not defined  ===> 找不到b这个变量
if(1){
    
    

    var a = 100;
        
    const c = 1;
}
 console.log(a); // 100
 console.log(c)  // 报错:c is not defined  ===> 找不到c这个变量

4. Is it allowed to declare variables repeatedly?

Let and const cannot declare variables with the same name in the same scope, but var can

code show as below:

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

5. Is there a temporary dead zone?

There is a temporary dead zone between let and const. That is, as long as there is a let command in the block-level scope, the variable it declares is "bound" to this area and is no longer affected by the outside.

code show as below:

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

6. 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. Variables declared by const must not change the value, which means that once const declares a variable, it must be initialized immediately and cannot be left for later assignment.
const f = 10;
// f= 11;
// console.log(f) //报错 不能进行重复声明

const obj = {
    
    
    name: '小明',
    age: 18
}
obj.age = 20
console.log(obj) //{ name: '小明', age: 20 }  
//const声明常量,不允许对变量重新赋值。对于引用类型的值而言,只要在栈内存保存的地址值不变即可。

Guess you like

Origin blog.csdn.net/zzDAYTOY/article/details/108431202