How JavaScript Works
JavaScript is among the most famous languages today. From Web, and Mobile to AI, JavaScript is everywhere. As a developer, you should know the ins and outs of the language. This knowledge will help you understand the language and make your logic more clear. So let's take a look at how JavaScript works.
Everything in JavaScript happens inside an Execution Context also known as Global Context. You can assume this Execution Context as a container inside which whole the JavaScript code is executed. Assume the Execution Context is like a big box and it executes JavaScript code in two phases:
Memory Creation Phase
In the Memory Creation Phase, all the variables and functions are stored as key-value pairs. The Memory Creation Phase is also known as the Variable Environment.
In the Memory creation phase, the memory will be allocated to all variables and functions inside the Global Execution Context. In this phase, variable declarations are scanned and made undefined.
Code Execution Phase
Code Execution Phase is the phase when code is executed one line at a time. The Code Execution Phase is also known as the Thread of Execution.
JavaScript is a synchronous single-threaded language. JavaScript can only execute one command at a time and in a specific order. It can only go to the next line once the current line has been finished executing.
In the code execution phase, the whole JavaScript program executes line by line. In this phase, all the calculations are done. In this phase, we allocate values to all variables. Previously it had an initial value of undefined.
JavaScript is treated to function as a mini program. So when JavaScript executes a function a new execution context is created. So just like the whole program runs in a Global execution context. To execute a function JavaScript creates a local execution context. Just like the Global Execution context has two phases, this local execution context is also having the same two phases.
领英推荐
After completion of function execution, the result is stored inside the Memory Component. Once the execution is done and the result is stored inside the Memory Component the local execution context is deleted from the code component.
Conclusion
So in this blog, we discuss how JavaScript works by breaking down its execution into two main phases within a Global Context:
In essence, JavaScript runs within a Global Context, which acts like a container for code execution, and it follows a two-phase process for managing variables and functions, as well as executing code. Additionally, functions create their own local execution contexts during their execution.
Sounds too complicated? Read the Simplified Versions
Read more about React & JavaScript
Follow me for more such content.
Building HoverConsole.com | Entrepreneur | Visionary
9 个月Good explanation