Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

New features of ES6 how to use the let and const commands

Shulou Source: shulou.com Published: 2022-05-31 13:31:47 09月23日 Update

This article mainly introduces the relevant knowledge of "how to use the new features of ES6 let and const commands". The editor shows you the operation process through an actual case. The operation method is simple and fast, and it is practical. I hope that this article "how to use the new features of ES6 let and const commands" can help you solve the problem.

1. Let command

① has no block-level scope in js, the variable scope declared by var is the whole function body, and let can play this role.

{let a = 1; var b = 2;} console.log (b); / / 2console.log (a); / / an is not defind

② and let can play this role. In js, the declaration of variables and functions will be promoted to the top of the current scope. This will lead to problems.

Var a = []; / / the function and variable I are declared first, while the global variable I is assigned to 10for (var I = 0; I < 10; iSuppli +) {a [I] = function () {console.log (I);} console.log (I); / / 10a [6] (); / / 10

The use of let solves this problem.

For (let I = 0; I < 10; iTunes +) {a [I] = function () {console.log (I);};} a [6] (); / / 6

Unlike var, ③ let does not have the phenomenon of variable promotion.

Console.log (a); / / an is not definedlet a = 1

④ let does not allow repeated declaration of the same variable within the same block-level scope

/ / error {let a = 10; var a = 1;} / / error {let a = 10; let a = 1;}

2. Const command

① const is also used to declare variables, but to declare constants. Once declared, the value of the constant cannot be changed.

② is the same as let and cannot repeatedly declare the same variable within the same block-level scope.

The scope of ③ const is the same as that of the let command: it is valid only within the block-level scope in which the declaration is located.

Const PI = 3.1415 console.log (PI); / / 3.1415//PI = 3; / / Assignment to constant variable. (constant cannot be assigned) / / const PI = 3.1 PI' has already been declared / Identifier 'PI' has already been declared about "how to use let and const commands, the new features of ES6", thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Tags: Function variable command same characteristic function constant knowledge problem industry different practical effective global content at the same time practical practical location article Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Shulou Technology Apple Huawei Xiaomi