This is the first day of my participation in Gwen Challenge
This article covers the basic usage and features of let and const, which can be pulled directly to 4.x
ES6 adds the let and const commands to declare variables. Let’s take a look at some of their features.
1. Let the order
1.1 Basic Usage
ES6 added the let command to declare variables. Its use is similar to var, but the declared variable is only valid within the code block in which the let command resides.
{
let testA = 'A'
var testB = 'B'
}
console.log(testB) // 'B'
console.log(testA) // testA is not defined
Copy the code
In the above code, the variable declared by var returns the correct value and the variable declared by let is not defined. Note that the variable declared by the LET is valid only in the code block in which it resides.
1.2 There is no variable promotion
-
The var command will have a variable boost (this article will not detail variable boost, interested can see Hu yui’s Github), that is, the variable can be used before declaration, the value of undefined. Logically, variables should not be used until the statement has been declared.
-
The let command changes the syntactic behavior by declaring variables that must be used after the declaration or an error will be reported.
console.log(wave); // undefined
var wave = 'wave'
console.log(sky) // ReferenceError: Cannot access 'sky' before initialization
let sky = 'sky'
Copy the code
1.3 Temporary dead zone
As long as the let command exists in the block-level scope, its declared variables are bound (more on how later) to the region, no longer subject to external influence.
var tmp = 123
if(true) {
tmp = '123'
let tmp
}
Copy the code
In the above code, the TMP variable exists globally. In the block-level scope, let declared a local variable TMP, causing the latter to bind to the block-level scope. Therefore, before the let declared the variable, the value of TMP would be assigned to an error.
ES6 specifies that if a block existslet
orconst
Commands, the variables that the block declares for these commands, form a closed scope from the start. Any time these variables are used before declaration, an error is reported.
In short, a variable is not available within a code block until it is declared using either let or const. This is grammatically known as a temporary dead zone. The main purpose is to reduce runtime errors and prevent the variable from being used before it is declared, leading to unexpected problems.
1.4 Non-repeatable declaration
Duplicate declarations will cause an error
2. The const command
2.1 Basic Usage
const
Declare a read-only constant. Once declared, the value of a constant cannot be changed.
const PI = 3.1415;
PI / / 3.1415
PI = 3;
// TypeError: Assignment to constant variable.
Copy the code
const
Declared variables must not change value, meaning they must be initialized and cannot be left for later assignment.
const foo;
// SyntaxError: Missing initializer in const declaration
Copy the code
const
withlet
As well as havingBlock-level scope
, and declared variables do not promote, there is also a temporary dead zone, can only be used after the declared position.
2.2 nature
What const actually guarantees is not that the value of the variable is fixed, but that the memory address to which the variable refers is fixed. For simple type data, the value is stored at the memory address that the variable points to. In the case of a reference type, a pointer to a memory address holds only a pointer to data. Const guarantees that the pointer is fixed, but does not control whether the data structure it points to is mutable.
const foo = {};
// Add an attribute to foo
foo.prop = 123;
foo.prop / / 123
// If foo points to another object, an error is reported
foo = {}; // TypeError: "foo" is read-only
Copy the code
3. Pay attention to
ES6 block-level scopes must have braces, and if there are no braces, the JavaScript engine assumes that there is no block-level scope.
// This is not the case
if (true) let x = 1;
// The second way is not error
if (true) {
let x = 1;
}
Copy the code
4. Block-level scope principle
Block-level scope (const) ¶ Block-level scope (const) ¶ Block-level scope (const) ¶
4.1 First, we need to start with scopes
Scope is the area in the program where variables are defined, and the location determines the lifetime of the variables. Generally speaking, it is the accessible scope of variables and functions, that is, scope controls the visibility and declaration cycle of variables and functions
Prior to ES6, there were only two types of scope: global scope and function scope
The lack of block-level scope causes a number of problems:
- Variables are covered
- Naming conflicts
- Variable ascension
- A memory leak
4.2 How is block-level scope implemented?
Now that we know that block-scoped variables can be declared via lets or const, how does ES6 support both variable promotion and block-scoped in a piece of code?
We need to reveal the answer from the perspective of the execution context.
JavaScript engines implement functional scope through variable environments, so how does ES6 implement block-level scope support on top of functional scope? You can start by looking at this code:
function foo(){
var a = 1
let b = 2
{
let b = 3
var c = 4
let d = 5
console.log(a)
console.log(b)
}
console.log(b)
console.log(c)
console.log(d)
}
foo()
Copy the code
When executing the above code, the JavaScript engine compiles it and creates the execution context, and then executes the code in order. We’ve explained how to create the execution context in previous articles, but the situation is a little different now. We’ve introduced the let keyword. The let keyword creates block-level scopes, so how does the let keyword affect the execution context?
Next, we will analyze the above code execution process step by step
The first step is to compile and create the execution context, as shown below:
By looking at the above picture, we can come to the conclusion that:
- through
var
Declared variables that are placed at compile timeThe variable environmentIn the - through
let
Declared variables are put into the lexical environment during compilation - Inside the function’s scoped block, variables declared by let are not stored in the lexical environment
To continue:
Can be seen from the diagram, when entering the function block, the scope of the scope block through the let statement variables that will be placed on the lexical environment, in a separate area of the variables in this area does not affect the outside of the scope of variables, such as in the scope statement face the variable b, within the scope of also declare the variable b, when performing the into the scope, They all exist independently.
In fact, inside the lexical environment, a small stack structure is maintained. The bottom of the stack is the outermost variable of the function. After entering a scoped block, the variables inside the scoped block will be pushed to the top of the stack. When the scope execution is complete, the information for that scope is popped from the top of the stack, which is the structure of the lexical environment. Note that when I say variables, I mean variables declared by let or const.
References:
-
Introduction to ECMAScript 6 Ruan Yifeng
-
Li Bing – Block-level scope: Var flaws and why let and const were introduced?