A scope in a function
Hide the internal implementation
- Why not put all variables and functions in global scope?
To avoid conflict
- Hiding variables and functions in scope avoids conflicts between identifiers of the same name.
Global namespace
- Many third-party libraries give variables unique names to prevent variable collisions.
Module management
Function scope
- An immediate function is one that does not require a function name and can be executed automatically.
Anonymous and named
- Distinguish between anonymous function expressions and function declarations: function declarations require function names, but function expressions do not.
- Anonymous function expressions have the following disadvantages:
- Anonymous functions have no name in the stack trace, which can make debugging difficult.
- There is no function name and only the expired arguments.callee reference can be used if recursion is required.
- Anonymous functions reduce code readability.
Execute the function expression immediately
- IIFE, abbreviation for immediately executing functions
- Execute the function immediately to pass parameters
- Invert the running order of the code: Window is the real argument
Block scope
- Distinguish whether the definition is inside or outside the block-level scope
The with keyword can form a block scope
try/catch
- Parameters in a catch form a block-level scope
- But if you declare var inside a catch, you’re still declaring it in global scope
Let the keyword
- The let keyword forms an implicit block-level scope relative to the explicit below.
- Variables declared by let are not promoted in block scope.
Garbage collection
- Block-level scopes make it clear to the engine that there is no need to save variables that are no longer needed.
The const keyword
- Const can also be used to create block-level scopes, but the value of the block-level scope is fixed. For reference addresses, the address cannot be changed, but the value can be changed.