Rabi Siddique
133 words
1 minutes
Lexical Scope in JS

Lexical Scope is the scope that is defined at lexing time.

The Engine starts looking for variables in the innermost scope first. Then it looks in the outer containing scopes, going up a level to the next nearest scope, and so on.

Scope lookup stops once it finds the first match. The same variables can exist in different layers of the nested scope, which is called shadowing.

Regardless of shadowing, the Engine starts the lookup from the innermost scope and works its way upwards until the first match is found.

No matter where a function is invoked from or how it is invoked, its lexical scope is always defined by where the function was declared.

Cheating the Lexical Scope at Runtime#

  1. eval function: Dynamically evaluates code, which can modify lexical scope.
  2. with statement: Extends the scope chain for a statement.
Lexical Scope in JS
https://rabisiddique.com/posts/lexical-scope-in-js/
Author
Rabi Siddique
Published at
2022-07-30