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!

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor

Zend Studio 13.0.1
Powerful PHP integrated development environment

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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software