This article mainly introduces the let and const commands in the new features of ES6, and analyzes the functions, usage methods and related precautions of the let and const commands in the form of examples. Friends in need can refer to it
This article describes the let and const commands in the new features of ES6 with examples. Share it with everyone for your reference, the details are as follows:
1. let command
① There is no block-level scope in js. The scope of the variable declared by var is the entire function body, and let can play this role
{ let a = 1; var b = 2; } console.log(b); // 2 console.log(a); // a is not defind
② And let can play this role. The declaration of variables and functions in js will be promoted to the current scope. Execution at the top. This will cause problems.
var a = []; //函数和变量i会最先进行声明,同时全局变量i经过for循环赋值为10 for (var i = 0; i < 10; i++) { a[i] = function () { console.log(i); }; } console.log(i);//10 a[6]();//10
Using let solves this problem
for (let i = 0; i < 10; i++) { a[i] = function () { console.log(i); }; } a[6](); //6
③ let is not like var, which will cause "variable promotion" phenomenon
console.log(a); // a is not defined let a = 1;
④ let is not allowed in the same block Within the level scope, declare the same variable repeatedly
// 报错 { let a = 10; var a = 1; } // 报错 { let a = 10; let a = 1; }
2. const command
① const is also used to declare variables, but the declaration is constant. Once declared, the value of a constant cannot be changed.
② Same as let, the same variable cannot be declared repeatedly in the same block-level scope.
③ The scope of const is the same as the let command: it is only valid within the block-level scope where the declaration is located.
const PI = 3.1415; console.log(PI); // 3.1415 //PI = 3; // Assignment to constant variable.(不能给常量赋值) //const PI = 3.1;// Identifier 'PI' has already been declared
Students who need to learn js please pay attention to the php Chinese websitejs video tutorial. Many js online video tutorials can be watched for free!
The above is the detailed content of New ES6 features you must know: Detailed explanation of let and const commands. For more information, please follow other related articles on the PHP Chinese website!