🌟 Scope

scope

  • Explanation: Scope is the accessibility of variables, functions, and objects in a specific part of the runtime code.
  • Scope: The biggest use of scope isSegregation variableVariables with the same name in different scopes do not conflict.
  • Features: Scopes are layered, with inner scopes having access to variables in outer scopes, but not vice versa.
  • Before ES6, JavaScript had no block-level scope, only global scope and function scope. With the advent of ES6, we have ‘block-level scope’, which can be embodied by the addition of the let and const commands.

Global scope

  • Explanation:Objects that can be accessed anywhere in the code have global scope.
  • Common:
  • 1) Outermost functions and variables defined outside the outermost function have global scope
  • 2) All variables that are not directly assigned are automatically declared to have global scope
  • 3) All properties of the Window object have global scope

Function scope

  • Explanation:A function scope is a variable declared inside a functionIn contrast to global scopes, local scopes are generally accessible only within fixed code snippets, most commonly within functions.

Block-level scope

  • Block-level scopes can be declared with the new let and const commands. Variables declared cannot be accessed outside the scope of the specified block.
  • Create:
  • 1) Inside a function
  • 2) Inside a code block (enclosed by a pair of curly braces)
  • Features:
  • 1) Declaration variables are not promoted to the top of the code block, and let/const declarations are not promoted to the top of the current code block
  • 2) Repeat statements are prohibited
  • 3) Bound block scope in loop

🌟 scope chain

Free variables

Variables not defined in the current scope

The scope chain