4.1 Scopes

The lexical scope (short: scope) of a variable is the region of a program where it can be accessed. JavaScript’s scopes are static (they don’t change at runtime) and they can be nested – for example:

  1. function func() { // (A)
  2. const aVariable = 1;
  3. if (true) { // (B)
  4. const anotherVariable = 2;
  5. }
  6. }

The scope introduced by the if statement (line B) is nested inside the scope of function func() (line A).

The innermost surrounding scope of a scope S is called the outer scope of S. In the example, func is the outer scope of if.