Learning a new programming language can be fun if we know how things are going underneath the hood. In this article we will see how things work around when it comes to execution of a JavaScript Program!
Well you might have heard that everything in JavaScript happens or takes place inside an execution context. Now what exactly is this execution context?? Well, to put it in simple terms we can say execution context is like a container that mainly contains two components viz Memory Component and Code Execution Component.
Basically, execution of a program takes place in two phases,
1.Creation Phase
2.Code Execution Phase
We will try to understand these phases with an example.
Consider the below code ,
var firstName='Shrushti';
var surname='Polekar';
function getFullName(firstName,surname){
const name=firstName+" "+surname;
return name;
}
var candidateFullName=getFullName(firstName,surname);
console.log(candidateFullName);
Step 1: Creation Phase
First of all a global execution context is created.
In this phase memory will be allocated to variables firstName and surname with a placeholder of undefined. The function getFullName will also get memory allocated with the actual block of code as placeholder.
Step 2: Code execution phase
In this phase the compiler will start executing the code line by line. The variables firstName and surname will be assigned the actual values ie Shrushti and Polekar. Now as soon as the compiler encounters the function call getFullName, a new execution context will be created and the again the same procedure will be repeated of memory allocation.
The function will perform the operation written in its block and return the string value. Thus the variable candidateFullName will get assigned the value -Shrushti Polekar.
After this the execution context will get discarded and remaining code will continue to execute. Finally the global execution context will also get discarded.
Thus like this the execution contexts are created , executed and discarded untill the global execution context is not finally discarded.
This was all about working of a JavaScript Code!!!
Happy Coding!
Top comments (2)
So basically every variable inside function is undefined until it gets assigned !
All right! This was something new for me.
After reading this I wonder though 🤔 how an asynchronous function works under the hood.