Preface
As we all know, es6 is the next generation standard of the JavaScript language and was officially released in June 2015. Its goal is to make the JavaScript language useful for writing complex large-scale applications and become an enterprise-level development language.
It perfects the naming specification of ES5, and it republishes two new ways of naming variables: let and const, but the variable declared by let only works in the code block where it is located.
This article will introduce to you two methods of naming ES6 variables. Let’s take a look at the detailed introduction together:
let a = 10; var b = 1; } a // ReferenceError: a is not defined. b // 1
1. The counter of the for loop is very suitable for let. For example, I encountered a problem before, which is that there are many lis in an ul. If you want to click on each li, which li is obtained.
for (let i = 0,len=; i < len; i++) { obj[i].addEventListener("click",function (){ (i) },false); }
var loops an object in the for loop and gets the length of the last object, and let solves that problem well and accesses the index of each li.
2. No variable promotion
The var command will have a "variable promotion" phenomenon, that is, the variable can be used before declaration and the value is undefined. This phenomenon is more or less strange. According to general logic, variables should be used after declaration statements.
To correct this phenomenon, the let command changes the syntax behavior, and the variables it declares must be used after declaration, otherwise an error will be reported.
// var situation(foo); // Output undefinedvar foo = 2; // let's(bar); // Error ReferenceErrorlet bar = 2;
const declares a read-only constant. Once declared, the value of the constant cannot be changed.
const PI = 3.1415; PI // 3.1415 PI = 3; // TypeError: Assignment to constant variable.
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 to be assigned later.
For const, if you only declare without assignment, an error will be reported.
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.
Summarize
The above is the entire content of this article. I hope that the content of this article will be of some help to everyone’s study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.