ES6 study notes: block-level scope
Scope Category
- Global scope
- Local scope
Block-level scope
Global scope example
var i=2;
for (var i = 0; i < 10; i++) {
}
console.log(i);//10
- Here there have been unintended consequences, such reason is caused by variable lift off
Example local scope
!(function () {
console.log(b);//undefined
var b = 2;
})()
- Why output undefined, rather than an error?
- Such results are unexpected variable lift caused, equivalent to the following code above.
!(function () {
var b;
console.log(b);//undefined
b=2;
})()
Here it is thrown out the question, what is a variable lift ?
JavaScript, functions and variable declaration will be promoted to the top most function.
JavaScript, variables can be declared after use, that is, variables can be declared before use again.
ES6 introduced the concept of block-level scope
//块级作用域使用方式
{
//...code
}
Note: Using var to declare variables from block-level scope restrictions, variable still result in improvement, and therefore
We introduce two new variables
- let
- Usage: declare a variable
- Features:
- Only valid block declaration
- It can not be repeated declarations in the same scope
- No variable lift
- Temporary dead zone
- const
- Usage: Declare a read-only variable (understood as a constant)
- Features: let the same with
- Precautions:
- While the variable declaration must be assigned immediately
- The statement is a simple type of data values, variable immutable
Essence: to ensure that variable to point to the memory address of the stored data does not allow changes
The simple type string, number, Boolean, as complex objects types, arrays, functions, be careful when it is declared const complex type objects
Examples of Use
- Example 1
if(true){
var a=10;
}
console.log(a);//10
- Example 2
if(true){
let a=10;
}
console.log(a);//error: a is not defined
- Example 3
{
let a=2;
}
{
let a=3;
console.log(a);//3
}
- Example 4
{
const a=2;
console.log(a);//2
a = 3;//error:"a" is read-only
}
- Example 5
{
const obj={
name:'小明',
age:18
}
console.log(obj);//{name:"小明",age:18}
obj.name="小红";
console.log(obj);//{name:"小红",age:18}
}