Skip to main content

Command Palette

Search for a command to run...

Let's understand JavaScript Execution Context

Published
•2 min read•View as Markdown
Y

An engineer by profession and a JavaScript Lover by heart.

First and foremost, I love writing code. Ever since writing my first program in C and manipulating it to produce the desired output. I believe in the power of programming to transform and improve the lives of people around the world.

My curiosity levels are as fresh as when I was a child. I believe in eternal learning and deliberate effort as they are the only way to become the smartest in the room. I am a good timekeeper, always willing to learn new skills and use them in real-life problems.

An ambitious individual with a desire to succeed. A Cricket fanatic. A student who likes to take risks and does not shy away from experimenting with various combinations in life. Striving to do a lot. Wish me good luck 🙏🏼

My primary interest is in Web Development and Mobile Application Development.

Tech Stack:- ReactJS, NextJS, NodeJS, MongoDB, GraphQL, Javascript Version Control:- Git, Gitlab

Whenever a JavaScript engine executes a script, it creates something called Global Execution Context(GEC). Even when you do not have a single line of code in a .js file and load it, you will have the Global Execution Context created.

There are two phases in Execution Context, i.e., Creation and Execution phases. **Let see this with an example:

var firstName = 'Yash';

function getName() { console.log("Hello World"); }

getName(); The creation phase:**

1) Creates a global object, i.e., window in the web browser or global in Node.js.

2) Creates a global variable called this.

3) Memory gets allocated for the variable name and the function getName().

4) The variable name gets initialized by a value called undefined. The function getName() gets placed directly into the memory

After the creation phase, the global execution context moves to the execution phase.

The execution phase:

During the execution phase, the JavaScript engine executes the code line by line. In this phase, it assigns values to variables and starts the execution of the function calls. So the value "Yash" is assigned to the variable firstName after that getName() function executes.

For every function call, the JavaScript engine creates a new Function Execution Context. The Function Execution Context is similar to the Global Execution Context, but it creates the arguments object that contains a reference to all the parameters passed into the function instead of creating the global object.

In our example, we do not pass any arguments. Hence the length is 0.

It uses a data structure called call stack to keep track of all the execution contexts, i.e., the Global Execution Context and Function Execution Contexts.

More from this blog

Yash Mantri

20 posts

An engineer by profession and a JavaScript Lover by heart