Based on JavaScript ES new features let and const keywords

Based on JavaScript ES new features let and const keywords

1. let keyword

1.1 Basic Usage

let is a new keyword added in ECMAScript 2015 , which is used to declare variables. Its usage is similar to var, but the difference is that the declared variables can only be used in the code block where they are located.

The syntax structure is as follows:

let var1 [= value1] [, var2 [= value2]] [, ..., varN [= valueN]];


Parameter Description:

var1, var2, …, varN : variable names. Must be a valid identifier.

value1, value2, …, valueN : initial values ​​of the variables. Can be any legal expression.

The sample code is as follows:

In the global scope, variables are defined

// define global variables var a = 100; // use the var keyword let b = 200; // use the let keyword console.log(a); // 100
console.log(b); // 200


We found that simply defining a global variable makes no difference.

Defining variables in block scope

For more information about block scope, please refer to this article.

// Define variables in block scope {
  var a = 100; // uses the var keyword let b = 200; // uses the let keyword }
console.log(a); // 100
console.log(b); // Throws an exception with the description ReferenceError: b is not defined


If let is used in a code block, the code block becomes a brand new scope and its variables cannot be accessed outside the scope.

The let keyword provided by ES6 is particularly suitable for use as a variable in for loop calculator. If this is done, the variable can only be used within the loop body, and an exception will be thrown outside the loop body.

The sample code is as follows:

// Define a loop body for (let v = 0; v < 10; v++) {
  console.log("This is a for loop"); // This is a for loop * 10
}
console.log(v); // Throws an exception with the description: ReferenceError: v is not defined


It is worth noting that the for loop has another special feature, that is, the part that sets the loop variable is a parent scope, and the loop body is a separate child scope.

The sample code is as follows:

for (let v = 0; v < 10; v++) {
  let v = 10
  console.log(v); // 100 * 10
}


The above result means that the two v are not in the same scope.

1.2 There is no variable promotion

If you use var to define a variable, the so-called variable commission will occur, as shown in the following code:

console.log(v); // undefined
var v = 100;


We use this value before the variable declaration, and it does not report an error, but the result is undefined. This is a strange logic. According to general logic, if it is used in this way, it should throw an exception.

In ECMAScript 2015 , the let keyword solves this strange phenomenon.

As shown in the following code:

console.log(v); // Throws an exception with the description ReferenceError: Cannot access 'v' before initialization
let v = 100;


In the above code, an exception will be thrown with the description that a variable cannot be used before being declared.

1.3 Temporary Dead Zone

As long as there are variables defined with the let keyword in the block-level scope, the variables declared by it will be bound to this area and will no longer be affected by the outside world. The sample code is as follows:

let v = 100; 
{
  console.log(v); // Throws an exception with the description ReferenceError: Cannot access 'v' before initialization
  // This variable is bound to the block-level scope, and this scope can only use this variable let v = 200;
}


ECMAScript 2015 clearly stipulates that if there is a let keyword in a block, the block forms an enclosing scope for the variables declared by these commands from the beginning. As long as you use these variables before declaring them, you will get an error.

In general, in a block-level scope, a variable is not available until it is declared using the let keyword. This is grammatically called a temporary dead zone , or TDZ for short.

1.4 Duplicate declarations are not allowed

The let keyword provided by ECMAScript 2015 does not allow repeated declarations, which is different from var. The sample code is as follows:

// Use var to declare variables var a = 100;
console.log(a); // 100
var a = 1000; // repeated declaration console.log(a); // 1000

// Use let to declare variables let b = 100;
console.log(b); // 100
let b = 1000; // Repeated declaration console.log(b); // Throws an exception with the following description: SyntaxError: Identifier 'b' has already been declared

If you declare it repeatedly, SyntaxError exception will be thrown.

1.5 Relationship with functions

The function parameters we use are equivalent to variables defined using the let keyword. If you use the let keyword again in the function body to re-declare a variable with the same name as the parameter, SyntaxError exception will be thrown. Of course, using let in the function body does not allow variable promotion

// Use let to declare variables let a = 100;
// define a function function fun(b) {
  // let b = 10; // throws an exception with the description: SyntaxError: Identifier 'b' has already been declared
  console.log(a); // Throws an exception with the description: ReferenceError: Cannot access 'a' before initialization
  let a = 200;
}
fun(20)


2. const keyword

2.1 Basic Usage

The const keyword is used to declare a constant. We can understand the constant generated by const keyword as an immutable let variable. Here, because the const keyword has all the characteristics of the let keyword, the immutable characteristic is added on the original basis.

The so-called constant is immutable after initialization and must be initialized when declared. The sample code is as follows:

const a = 2
a = 3 // throws an exception const b // uninitialized throws an exception

However, when we use const to initialize an object or array, we can change the value inside it, and it does not report an error. The sample code is as follows:

const arr = []
arr[0] = 100 
console.log(arr) // [100]
const obj = {}
obj.name = 'A bowl of Zhou'
console.log(obj) // {name: "Yiwan Zhou"}

The reason for this problem is that the const keyword actually guarantees not that the value of the variable cannot be changed, but that the memory address pointed to by the variable cannot be changed. For simple data types, such as String , Number , and Boolean , these values ​​are stored in the memory address pointed to by the variable, so it cannot be modified a second time.

However, for composite data types, mainly Array and Object , the memory address pointed to by the variable only stores a pointer. Const can only ensure that the memory address pointed to by this pointer is fixed. As for whether the data structure stored in the memory address it points to is variable, it cannot be controlled at all.

In actual development, we avoid using the var keyword and instead use the const keyword. When we need to use variables, we use the let keyword.

This is the end of this article about the new features of JavaScript ES, let and const keywords. For more information about the new features of ES, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of the differences between var, let and const in JavaScript es6
  • Usage and difference between let and const in ES6 specification in JavaScript
  • Detailed explanation of the differences and usage of var in JavaScript and let and const in ES6 specifications
  • Detailed comparison of const, let and var in JavaScript ES6
  • The difference between var definition and non-var definition in JS variables and let command and const command in es6

<<:  Implementation steps for enabling docker remote service link on cloud centos

>>:  The space is displayed differently in IE, Firefox, and Chrome browsers

Recommend

Introduction to the process of installing MySQL 8.0 in Linux environment

Table of contents Preface 1. Linux changes the yu...

Html page supports dark mode implementation

Since 2019, both Android and IOS platforms have s...

Writing High-Quality Code Web Front-End Development Practice Book Excerpts

(P4) Web standards are composed of a series of sta...

MySQL 5.7 installation and configuration tutorial under CentOS7 (YUM)

Installation environment: CentOS7 64-bit, MySQL5....

How to add website icon?

The first step is to prepare an icon making softwa...

How to manage cached pages in Vue

Table of contents Problem 1: Destruction 1. How t...

How to configure mysql on ubuntu server and implement remote connection

Server: Ubuntu Server 16.04 LSS Client: Ubuntu 16...

js code that associates the button with the enter key

Copy code The code is as follows: <html> &l...

Detailed process analysis of docker deployment of snail cinema system

Environmental Statement Host OS: Cetnos7.9 Minimu...

Detailed explanation of web page loading progress bar (recommended)

(When a web page is loading, sometimes there is t...

How to query whether the mysql table is locked

Specific method: (Recommended tutorial: MySQL dat...

Detailed installation and configuration tutorial of mysql5.7 on CentOS

Install Make sure your user has permission to ins...