What is a block?
A block is a statement (or compound statement) that combines zero or more statements. The block is defined by a pair of braces {}
Block declaration: {StatementList}
2. What is block-level scope?
When var or function declarations are made in non-strict mode, variables declared by var or functions created in non-strict mode have no block-level scope.
Here’s an example:
var x = 1; { var x = 2; } console.log(x); // The output is 2, because var has no block-level scopeCopy the code
while
let x = 1; { let x = 2; } console.log(x); // The output is 1. Let is block-scopedCopy the code
3. Comparison of let and const
Let and const both have block-level scope, as shown below:
If there were no block-level scope, the output would be 2, because there is block-level scope, so the output would be 1.
4. What is variable promotion?
Look at another blog post: Variable promotion
5. Var, let, const
Var, let, const comparison | The same | The difference between |
---|---|---|
var | ||
let | ||
const |
-
Block-level scope
- Var does not, let and const do.
-
Initialize the
- Variables defined by const must be initialized and cannot be modified
- The variable defined by var can be modified. If it is not initialized, it is undefined
- Let is a block-level scope. If defined internally, let has no effect on the outside of the function.
-
Variable ascension
- Let /const has no variable promotion
- Var is variable enhanced
Personal understanding is very simple, welcome criticism, correction, thank you.