DEV Community

Cover image for Lexical Scope System & How it works In JavaScript
Ahmad Noor
Ahmad Noor

Posted on

Lexical Scope System & How it works In JavaScript

Scope

What is Scope ?

friend of Js Engine, that collects and maintains a look-up list of all the declared identifiers (variables), and enforces a strict set of rules as to how these are accessible to currently executing code.
What is Lexical Scope & How it Works ! ?
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.

To visualize the process of nested Scope resolution, I want you to think of this tall building.
Let’s consider this block of code:

Code_Snippet

Bubble 1️⃣ encompasses the global scope, and has just one identifier in it: foo.
Bubble 2️⃣ encompasses the scope of foo, which includes the three identifiers: a, bar and b..
Bubble 3️⃣ encompasses the scope of bar, and it includes just one identifier: c..

Scope bubbles are defined by where the blocks of scope are written, which one is nested inside the other, etc. let’s just assume that each function creates a new bubble of scope.
The bubble for bar is entirely contained within the bubble for foo, because (and only because) that's where we chose to define the function bar.
Notice that these nested bubbles are strictly nested. We’re not talking about Venn diagrams where the bubbles can cross boundaries. In other words, no bubble for some function can simultaneously exist (partially) inside two other outer scope bubbles, just as no function can partially be inside each of two parent functions.

Code_Snippet

Here variable b will resolve lexically because javascript has lexical scope system💯
it does not matter where from where function is calling it only depends where it’s declared 👀
function bar is declared in foo scope but we are calling this function from foo1 scope 🙉

Conclusion!

lexical scope is write-time.Lexical scope cares where a function was declared.

Top comments (0)