How is code in JavaScript executed? What is Execution Context and Call Stack?
Java is to JavaScript, as Gulab is to Gulab Jamun.
This was the statement I came across which was written by Akshay Saini Sir
And I became interested in knowing JavaScript and went through the entire series of Namaste JavaScript!!!
I had lots of questions such as is JavaScript Synchronous or Asynchronous? Is JavaScript single-threaded or multi-threaded? and this series cleared all my doubts!!
So here, I am going to summarise the basic concepts of JavaScript which I learned from the videos!!!
This article covers a lot of concepts such as execution context, call stack, how are programs executed in JavaScript, etc.
So let’s get started!!!!!
JavaScript is an asynchronous, single-threaded language.
It is an asynchronous single-threaded language because it executes one line of code at a time and in a specific order.
So here the question arises that what happens when you run a JavaScript code?
It’s very interesting to understand it!!
Let’s begin!!
Everything in JavaScript happens inside a global execution context.
Execution of code is divided into two phases: Memory Creation Phase and Code execution phase.
In the memory creation phase, JavaScript allocates memory to variables and functions. In the case of variables, undefined is assigned as a placeholder while in the case of functions entire code of the function is stored.
In the code execution phase, code gets executed line by line. Here, undefined is replaced by the values of the variables.
How are functions executed in JavaScript??
Functions are very beautifully executed in JavaScript.Every time a function is invoked, a new execution context is created. After the function is executed completely, control returns to the place where the function is invoked.
What is a Call stack in JavaScript?
Whenever any JavaScript code runs, its Global Execution context is pushed inside Call Stack. Whenever a function is invoked a new execution context is created and pushed into the call stack.
After the function finishes execution, the execution context is popped out of the call stack.
Call stack maintains the order of execution Contexts.
The call stack is also known by many different names such as Execution Context Stack, Program Stack, Control Stack, Run time Stack, Machine Stack, etc.
If you wish to see the video from where I got to know these concepts, you can check it on this video link in the Namaste JavaScript series by Akshay Sir.
Please share your feedback on this article and if you liked it share it will all your friends!!
In the upcoming articles, I will be writing about what is hoisting in JavaScript and keywords such as let, const, and var.