The following editor will bring you a brief discussion of the new features of ECMAScript6: let and const. Let me share it with you now and give it as a reference for everyone.
Next, let’s introduce the new feature “let” in es6. First of all, this thing is actually similar to the var command, which is used to declare variables, but the declared variables are only valid within the code block where the let command is located (this involves block-level scope) Concept, however, this concept was also proposed in es6. I will talk about it later. PS: In other programming languages, there has been block level for a long time)
The two pictures above reflect that the variables declared by let are only valid within the code block where the let command is located. Here’s an example:
# Do you notice the difference? Variables declared by var are valid in the global scope. In each cycle, the new i value will overwrite the old value, causing the final output to be the i value of the last round (of course, closures can also be used to solve this problem. [Third picture]). If you use let, the declared variable is only valid in the block-level scope, and the current i is only valid in this cycle, so i is actually a new variable every time it loops. During this period, I discovered a more magical thing, please look at the picture below:
##Note:①,let Unlike var, the phenomenon of "variable promotion" will occur, so it must be declared before use, otherwise an error will be reported.
②. Temporary dead zone (TDZ). As long as there is a let command in the block-level scope, the variables it declares will be bound to this area without external influence. Simply put, in a code block, variables cannot be used until they are declared using the let command. Example:function itself is within its block-level scope. Notice! Notice! Notice! Important things to say three times: (If it is in strict mode, functions can only be declared in the top-level scope and inside the function. In other cases [such as if statements and loop statements] an error will be reported) :
Note: ① In terms of scope, it is actually the same as let scope: it is only valid within the block-level scope where the declaration is located;
②. The constants declared by the const command also do not have "variable promotion" and also have a "temporary dead zone", which must be declared before they can be used. ③. Const cannot declare constants repeatedly. Comprehensive example:The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
php construct() function introduction and usage details
constAnt function introduction and usage details
JS variable declaration var,let.constUsage details
The above is the detailed content of ECMAScript6 new features let, const (graphic tutorial). For more information, please follow other related articles on the PHP Chinese website!