The story of lexical environment and execution context in JavaScript
This is the 2/30 solution plus concept for leetcode 30 days of JS more to come I’ll add link to problem and previous article at the end!
As you might know every time any program runs on any machine it creates a call stack and in that it creates the very first
Global execution context(GEC) which can contain few preloaded Objects and that totally depends on the engine and platform and that can also be called it’s Lexical Environment after the GEC is the thread of excution or code execution starts there are few key things to know before exploring the code
- Every varaible or function which is defined outside of any other function is available in lexical environment of GEC
- You cannot access the members of child lexical environment i.e which a function creates when it’s executed
- But child members can access the members of parent lexical environment
- after the execution of a function ends it’s lexical enviroment is destroyed and when the whole program ends GEC’s lexical environment is destroyed
- But if we have any closure function it will preserve the lexical enviroment of parent until it’s done execution
So combining the above concepts one can easily understand when we do
n++
in code the inner function can update the member of parent function which is
var createCounter = function(n)
One more important point to note here is that arguments passed in a function are usually by value but you can pass by reference for Arrays and Objects(Maps)
Hence every time we call the function like this
const counter = createCounter(10) //lexical env created for function
counter() // 10
//env preserved of createCounter,
//updated n and returned and then
//lexical env for local function is destroyed
counter() // 11
counter() // 12
Code -
/**
* @param {number} n
* @return {Function} counter
*/
var createCounter = function(n) {
return function() {
return n++
};
};
/**
* const counter = createCounter(10)
* counter() // 10
* counter() // 11
* counter() // 12
*/
Conclusion
Understanding how the program is initiated in JS and how the memory model works is fasinating and crucial in understanding how it would behave The GEC and lexical env is concepts which JS uses and then Automatically collects Garbage using garbage collector which usually uses a line sweep algorithm the JS interpreter also assigns memory before the execution starts for some members but maybe lets keep it bite sized and keep it for next.
Problem — https://leetcode.com/problems/counter/description/
Prev-Article — https://varnitsharma-102.medium.com/javascript-can-return-functions-what-8622fc8ff9c