ES6 new features - var, let, const

In es5, there are only the concepts of global scope and function scope. In es6, the concept of block-level scope is proposed, which is the area wrapped by {}.

 

Table of contents

1. The characteristics of var

2. The characteristics of let and const

3. Other features of const


1. The characteristics of var

  • var exists variable hoisting

Variable promotion is to promote the variable declared by var to the first declaration of the scope, and then get the value of undefined, while there is no variable promotion for let and const.

//就是在未运行到声明变量的代码之前使用该变量不会报错。
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;
  • Variables declared by var will be mounted on the window, let and const will not
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. The characteristics of let and const

  • let and const are block-level scopes, variables declared using let outside the block-level scope will report an error
if(1){
    var a = 13;
    let b = 10;
}
console.log(a); // 13
console.log(b)  // 报错:b is not defined  ===> 找不到b这个变量
  •  let and const cannot be declared repeatedly, var can be declared repeatedly, and the result will be overwritten by the assignment of the last declaration
var a = 100;
console.log(a); // 100
//再次声明
var a = 10;
console.log(a); // 10

let a = 100;
let a = 10;//  控制台报错:Identifier 'a' has already been declared  ===> 标识符a已经被声明了。

3. Other features of const

  • When const is declared, it must be assigned a value, and null placeholders cannot be used
  • The value after the const declaration is not allowed to be modified, except for the complex type object
const a = 2;
a = 5 //报错 Uncaught TypeError: Assignment to constant variable.

const arr = [1,2,3]
console.log(arr) //[1,2,3]
arr[1] = 4;
console.log(arr) //[1,4,3]

Why can complex types be modified?

Because the complex type is stored on the heap, only the pointer of the reference is stored on the stack. As long as the reference address does not change, the const error will not be triggered.

Guess you like

Origin blog.csdn.net/m0_37756431/article/details/123188587