What is scope?
MDN says that a scope is the context in which the current value and expression are “visible” or accessible.
What kinds of scopes are there?
Variables have three types of scope: global scope, local scope, and ES6 block-level scope.
- Variables defined outside of a function, variables not directly assigned in “strict mode”, and properties of window objects all have global scope.
- The local scope is also called the function scope, that is, the variables defined inside the function only have the local scope inside the function, and the function parameters are also local variables within the function and have the local scope.
- Block-level scope means that a variable defined by let in a non-function {} has only the block-level scope inside {}.
What is a scope chain?
If A function B is declared in function A, then the scope of A is referenced when B is created, forming what is called A function scope chain. When the variable is not found in its own scope, it is searched up the scope chain, and if the variable is still not found in the global scope, an exception is thrown.
How to use scope chain knowledge to optimize performance?
The deeper the scope chain is, the slower the read and write will be, and the slower it will be to find global variables, so when writing code:
Use global variables as little as possible and local variables as much as possible.
If a cross-scoped variable is referenced more than once, it should be stored as a local variable before being used.
What is js execution context?
When JS code is executed, there are three execution contexts
- Global execution context
- Function execution context
- Eval Execution context
There are three important properties in each execution context
- A variable object (VO) that contains variables, function declarations, and function parameters
- Scope chain (JS is lexically scoped, that is, the scope of a variable is determined at definition time)
- this
What is variable promotion?
JS variables are created through three stages: create, initialize, and assign. To put it simply, variable promotion is a mechanism that moves a variable in the create/initialize/assign phase to the front of the scope.
At which stage did let, const, var and function raise the variables respectively?
- The “creation” process of the LET has been improved, but initialization has not. (Many people call this a transient dead zone for LETS.)
- The “creation” of const is improved, but the initialization is not.
- Var “creation” and “initialization” have been improved.
- Function ‘create’, ‘initialize’ and ‘assign’ have all been improved.