JS 101: Execution Context in JavaScript
Everyone can write JavaScript code but knowing how it works will always help you understand those issues which consume your entire day and can even want you reconsider your entire career choice.
Don't worry by the end of this article, you will at least know, the lifecycle of JavaScript, and have a basic understanding of something known as Execution Context.
JavaScript code is compiled using something known as Execution Context.
Execution Context has two main phases:
1- Memory Allocation Phase or Variable Environment
2- Code Execution Phase or Thread Execution
Memory Allocation Phase:
In Memory Allocation Phase, Javascript stores each variable we declare as a key-value pair.
All the variables are stored as keys while their value goes as undefined.
Considering the code above, memory allocation would store something like this:
age = undefined
name = undefined
and for function, JavaScript stores the entire code of the function as its value, we will get back to this later.
The above code will be something like this:
PrintMyName: ()=>console.log("My name is Ahmad")
Note: The Memory allocation phase is also responsible for Hoisting in JavaScript…
Code Execution Phase:
Now, after we have stored all variables and functions in the memory allocation phase, JavaScript proceeds to the Code Execution phase and starts to execute the code line by line...
Taking the following snippet as our example to understand better.
In line 1, JavaScript assigns the name variable the value Ahmad.
similarly, in line 2, JavaScript assigns the age variable the value 24.
Now when the variable is assigned a value, the key-value pair in the variable environment is updated the value is updated.
In line 3, the value to the function is already assigned, so the JavaScript compiler moves forward to line 5.
Since line 5 is invoking the function PrintMyName, now this is where an interesting thing happens, JavaScript considers each function as a new Execution Context, having its variable environment and its own thread of execution
PrintMyName creates another execution context inside our main execution context, which means, both phases will run again but now for this execution context.
In our simplified example, we only have the console log our name so it would be pretty straightforward and once all the code inside the execution context is completed, the execution context gets deleted from the stack…
Conclusion:
Understanding JavaScript Execution is not that difficult and keeping Variable Environment and Thread Execution in mind will pretty much help you a lot in day to day job as a JavaScript Developer.
Connect with me:
Twitter
Portfolio
Regards,
Ahmad Mustafeen,
Software Engineer at Geeks of Kolachi