Lexical Environment in JavaScript

Nilanga Virajith
2 min readJul 29, 2022

--

By definition, lexical environment is a data structure that holds the identifier-variable mapping. So if we take a simple function with variables inside it, the lexical environment is holding the identifier-variable mapping of those variables.

The exciting thing here is that in JavaScript the lexical environment of a function holds the identifier-variable mapping of its parent as well. Simply put, the lexical environment of a function is the combination of the local memory and its parent's lexical environment.

Let’s dig in using an example without focusing on the definitions and jargon.

Focus on the below code snippet.

var c = 3;function parent(){
var a = 1;

function child(){
var b = 2;
console.log(b);
console.log(a);
console.log(c);
}

child();
}

parent();

Let’s look at the call stack in parallel.

When we execute the above piece of code, the function child tries to find the variable b inside its local memory. Since it’s there, it logs b on the console. Then it tries to find the variable a inside its local memory and it’s not there. So it tries to find a inside its parent’s local memory because the function child has the local memory of its parent in its own lexical environment. The same thing happens when trying to log the variable c because the function child inherits the memory of the global execution context through the lexical environment of the function parent because the global execution context is the parent of the function parent.

That’s all there is to know about the lexical environment in JavaScript. A pretty simple but very useful feature.

Thank you for reading!

If you like what you read, please hit the clap button and show some support.

--

--