JavaScript Execution Context – How JS Code Runs Behind the Scenes
Before understanding what JavaScript Execution Context is, we need to know how and in which environments we can run JavaScript code.
First of all, we can run JavaScript in two environments:
- Through the Browser
- Through the Node.js
How does JavaScript code run on our computer?
When we write JavaScript code on our computer and then try to run it, the code first goes to either the Browser or Node.js.
However, the JavaScript code we write is not directly understood by the Browser or Node.js. At this point, both send the code to the JavaScript Engine built into them. There are different types of engines, for example:
- V8 Engine in Google Chrome,
- SpiderMonkey in Mozilla Firefox,
- V8 Engine in Node.js, etc.
Next, the JavaScript Engine compiles the JavaScript code into machine code. This machine code is then sent to the computer, which executes it, and we see the output displayed.
As programmers, we need to have a good understanding of this intermediate step, i.e., how the JavaScript Engine compiles JavaScript code into machine code.
So, now we need to understand how the JavaScript Engine works. The JavaScript Engine works in two ways to convert code into machine code. First one is Interpretation and the second one is Compilation. So, what are Interpretation and Compilation?
What is Interpretation, and How Does it Work?
Interpretation is the process of reading all the source code written in a high-level language line by line and converting each line into machine code immediately after reading it. If there is an error while reading a line of code, the process stops right there, making it easy for the programmer to identify the error. This makes debugging straightforward. However, since this process reads the code line by line, it is comparatively slower.
What is Compilation, and How Does it Work?
Compilation is the process of converting all the source code written in a high-level language into machine code at once. In this case, even if there are errors in the code, it will still compile and only show errors at runtime. As a result, it becomes harder for the programmer to identify the errors, making debugging more challenging. However, since the entire source code is converted into machine code at once, this process is comparatively faster. So now, the question arises: Is JavaScript a compiled or an interpreted language?
Is JavaScript a Compiled or an Interpreted Language?
Initially, JavaScript was primarily considered an interpreted language. However, since this process was quite slow, modern JavaScript engines began using a new technique that combines both interpretation and compilation, known as Just-In-Time (JIT) Compilation. This process combines interpretation and compilation to convert code into machine code. As a result, it is much faster and easier to debug compared to older methods.
To understand how JavaScript’s Just-In-Time (JIT) Compilation works, we need to understand JavaScript’s Execution Context. Let’s now try to understand JavaScript’s Execution Context.
JavaScript Execution Context
First, take a look at the following code example.
Code Example
var a = 1; function one() { console.log(a); function two() { console.log(b); var b = 2; function three(c) { console.log(a + b + c); } three(4); } two(); } one();
Output
1 undefined 7
When we ran the code, we tried to print the b variable before it was declared inside the two() function, and the output was undefined. However, no error occurred. The question arises: how did the b variable have the value undefined? The answer lies in the JavaScript Execution Context. Now, we will explore JavaScript Execution Context in more detail.
There are two types of Execution Context in JavaScript:
- Global Execution Context
- Function Execution Context
Each Execution Context goes through two phases: Creation Phase and Execution Phase.
Global Execution Context
When we run JavaScript code, the first thing that happens is the Global Execution Context. This context first goes through its Creation Phase, where several things happen:
Creation Phase
- A Global Object is created.
- A this object is created and assigned the value of the Global Object.
- A Variable Object is created, where all functions and variables are declared. The variables are assigned undefined as their value, and the functions are assigned references to their respective functions.
Once the Creation Phase completes, the Global Execution Context moves to the next phase: Execution Phase, where more steps occur.
Execution Phase
- The variables that were declared in the Creation Phase and initialized with undefined are now assigned their respective values.
- The functions declared in the Creation Phase, which were stored as references, are now called and executed.
Function Execution Context
When the functions referenced during the Execution Phase of the Global Execution Context are called, each function creates its own Function Execution Context. Just like the Global Execution Context, the Function Execution Context also goes through a Creation Phase, where several steps occur:
Creation Phase
- A parameter object is created for the function.
- A this object is created and assigned the value of the Global Object.
- A Variable Object is created, where all functions and variables are declared. The variables are assigned undefined as their value, and the functions are assigned references to their respective functions.
Once the Creation Phase is completed, the Function Execution Context moves to the Execution Phase, where more steps occur.
Execution Phase
- The variables declared in the Creation Phase, which were initialized with undefined, are now assigned their respective values.
- The functions declared in the Creation Phase are now called and executed.
Function Execution Context in Nested Functions
When functions are called within other functions, a new Function Execution Context is created for each of these functions. Each Function Execution Context then goes through both the Creation Phase and Execution Phase. This process continues for each function called inside another function, and each function will go through these phases separately.
Let's look at the diagram below.
We have seen that both the Global Execution Context and Function Execution Context go through certain steps. The only difference is that, in the Global Execution Context, the first step is to create the global object, whereas, in the Function Execution Context, the first step is to create a parameter object for the function.
Now, the question arises: how does JavaScript manage these Execution Contexts when they are created for both the global context and each function?
Managing Execution Contexts with the Execution Stack
To manage these contexts, JavaScript uses a data structure called the Execution Stack. The Execution Stack stores contexts in a stack-like manner: first, the Global Execution Context, followed by each Function Execution Context. When all the execution contexts are stored in the stack, JavaScript processes them one by one, starting from the top of the stack.
Scoping with let and const
It is important to note that when we declare variables with let or const inside a global or function scope, these variables are not stored in the Variable Object during the Creation Phase, and they are not initialized with undefined. Instead, these variables are directly declared and assigned their values in the Execution Phase.
Consider the following code example:
Code Example
var a = 1; function one() { console.log(a); function two() { console.log(b); var b = 2; function three(c) { console.log(a + b + c); } three(4); } two(); } one();
If we run this code, we will encounter a ReferenceError. This is because we are trying to print the value of the b variable before declaring it, and since b is declared using const, it behaves differently from regular variables. Variables declared with const or let are not stored in the Variable Object during the Creation Phase, which is why we get an error when trying to access them before they are assigned a value.
Conclusion
I hope this explanation of how JavaScript works and what happens during its Execution Context phases has provided you with a clearer understanding. In the next lesson, we will explore another JavaScript topic.
You can connect with me on GitHub and Linkedin.
The above is the detailed content of JavaScript Execution Context – How JS Code Runs Behind the Scenes. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...
