This is the second day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021
Block-level scope
The ES2015 standard has added block-scoping. In this article, we will look at what block-level scopes are.
Variables declared through var or function declarations created in non-strict mode have no block-level scope. Variables declared in a block are not only scoped within the function or script tag they are in; the effects of the set variable persist beyond the block itself.
Block-level scope is used to combine zero or more statements, and the block is defined by a pair of braces.
How to use
var
The statement
var name = 'also laugh';
{
var name = 'slifree';
}
console.log(name); // slifree
Copy the code
Var declares variables that have no block-level scope.
let
The statement
let name = 'also laugh';
{
let name = 'slifree';
}
console.log(name); / / also smiled
Copy the code
Variables declared by let are block-scoped, and only variables of the current scope can be retrieved. If two identical variables are declared by let in the same scope, an error will be reported as follows:
SyntaxError: Identifier 'name' has already been declared
Copy the code
If we wrap a separate scope with {} as in the code above, no errors are reported.
const
The statement
let const = 'also laugh';
{
let const = 'slifree';
}
console.log(const); / / also smiled
Copy the code
The use of const is similar to let, but it is different from let, and this is where we need to pay attention.
Matters needing attention
Let declares a variable whose value can be changed; A variable declared by const, whose value generally cannot be changed. Const is a constant and cannot be changed if the data is of an underlying type, as follows:
const name = 'also laugh';
name = 'slifree';
Copy the code
In this case, an error message is displayed as follows:
TypeError: Assignment to constant variable.
Copy the code
If the data is of reference type, it may be changed as follows:
Do not use it this way, otherwise an error will be reported
const obj = {};
obj = { name: 'also laugh' }
Copy the code
You can change the value in this way
const obj = {};
obj.name = 'also laugh'
console.log(obj); // {name: 'also laugh'}
Copy the code
conclusion
- In the project, the variables we define have a specific meaning and are not allowed to be defined repeatedly, so we generally use
let
Declare variables. const
It is used to declare a constant, meaning that the value of a variable we define will not change.
If you want to learn more about ES features, go to ES2015+ Fragmentation Learning, taking a step forward every day, which is the directory entry for all the articles.