ES6 let and const

1. Introduction

ES2015(ES6) added two important JavaScript keywords: let and const.

Variables declared by let are only valid in the code block where the let command is located.

const declares a read-only constant. Once declared, the value of the constant cannot be changed.

Two, let usage

1. Basic usage

For loop counter, it is suitable to use let command

for (let i = 0; i < 10; i++) {
  // ...
}

console.log(i);
// ReferenceError: i is not defined

2.let features

There is no variable promotion
let There is no variable promotion, var will be variable promotion

console.log(a);  //ReferenceError: a is not defined
let a = "apple";
 
console.log(b);  //undefined(b声明已提升但未赋值)
var b = "banana";

Block scope

{
  let a = 0;
  var b = 1;
}
a  // ReferenceError: a is not defined
b  // 1

Temporary Dead Zone
As long as there are let and const commands in the block-level scope, the variables declared by it are "bound" to this area and are no longer affected by the outside.

var tmp = 123;

if (true) {
  tmp = 'abc'; // ReferenceError
  let tmp;
}

Cannot repeat

let a = 1;
let a = 2;
var b = 3;
var b = 4;
a  // Identifier 'a' has already been declared
b  // 4

Three, const usage

1. Basic usage

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.

const foo;// SyntaxError: Missing initializer in const declaration

const PI = 3.1415;
PI // 3.1415
PI = 3;// TypeError: Assignment to constant variable.

2. Essence

What const actually guarantees is not that the value of the variable cannot be changed, but that the data stored in the memory address pointed to by the variable cannot be changed. For simple types of data (numerical value, string, Boolean value), the value is stored at the memory address pointed to by the variable, so it is equivalent to a constant. But for composite data (mainly objects and arrays), the memory address pointed to by the variable is only a pointer to the actual data. const can only guarantee that the pointer is fixed (that is, it always points to another fixed address) , As for whether the data structure it points to is variable, it is completely uncontrollable. Therefore, you must be very careful when declaring an object as a constant.

const foo = {};

// 为 foo 添加一个属性,可以成功
foo.prop = 123;
foo.prop // 123

// 将 foo 指向另一个对象,就会报错
foo = {}; // TypeError: "foo" is read-only

Four, ES6 six ways to declare variables

ES5 has only two ways to declare variables: var, function

ES6 has new additions to ES5: let, const, import, class

Guess you like

Origin blog.csdn.net/qq_41466440/article/details/111468029