top of page
Search

Lexical Scope?? What is it? How is it used in Javascript

  • panthakiurmez
  • Apr 7, 2023
  • 2 min read

We define “scope” as the set of rules that govern how the engine can look up a variable by its identifier name and find it, either in the current scope, or in any of the nested scopes it’s contained within.

There are two predominant models for how scope works : Lexical Scope & Dynamic Scope


But let us first understand how Scope Lookups work?

Scope look-up stops once it finds the first match. The same identifier name can be specified at multiple layers of nested scope, which is called “shadowing” (the inner identifier “shadows” the outer identifier). Regardless of shadowing, scope look-up always starts at the innermost scope being executed at the time, and works its way outward/upward until the first match, and stops.


So how is lexical scope different?

No matter where a function is invoked from, or even how it is invoked, its lexical scope is only defined by where the function was declared. The lexical scope look-up process only applies to first-class identifiers, such as the a, b, and c. If you had a reference to foo.bar.baz in a piece of code, the lexical scope look-up would apply to finding the foo identifier, but once it locates that variable, object property-access rules take over to resolve the bar and baz properties, respectively.


Review

Lexical scope means that scope is defined by author-time decisions of where functions are declared. The lexing phase of compilation is essentially able to know where and how all identifiers are declared, and thus predict how they will be looked up during execution. Two mechanisms in JavaScript can “cheat” lexical scope: eval(..) and with. The former can modify existing lexical scope (at runtime) by evaluating a string of “code” that has one or more declarations in it. The latter essentially creates a whole new lexical scope (again, at runtime) by treating an object reference as a scope and that object’s properties as scoped identifiers.

The downside to these mechanisms is that it defeats the engine’s ability to perform compile-time optimizations regarding scope look-up, because the engine has to assume pessimistically that such optimizations will be invalid. Code will run slower as a result of using either feature.

Don’t use them.

 
 
 

Comments


Post: Blog2_Post
bottom of page