Understanding the Javascript Engine: How Javascript Works

Understanding the Javascript Engine: How Javascript Works

A Comprehensive Look at the Inner Workings of the Javascript Engine

In simple words, Javascript is a language that can only do one thing at a time and in a specific order.

In more technical terms javascript is a synchronous single-threaded language.

Here, Single-threaded means javascript can only execute one command at a time whereas Synchronous means that javascript has to do things in a certain order and it can only move on to the next command once it has finished the command thing.

Global Execution context

Global Execution context is like a box with two components that keeps track of all code.

  • Memory (variable environment) where variables and functions are stored as a key-value pair.

  • Code (thread of execution) where all the code gets executed one line at a time.

What happens when you run a piece of code in Javascript?

When you run a piece of code the Global Execution Context is created in two phases.

  • Memory Allocation Phase

  • Code Execution Phase

During the Memory Allocation Phase variables and functions are allotted space in the memory component of the global execution context. Variables are assigned the value undefined and functions are assigned their function definition itself when they are first created.

The Code Execution Phase is the second phase of the execution process following the memory allocation phase. This is where the javascript skims through the code line by line and determines what actions to take. For eg:

If the code has a variable (let num = 5), it will reassign its value from undefined to the now skimmed value(5). So num = undefined is now changed to num = 5 in memory of the execution context.

This process continues until the program is complete.

Call Stack

Our program can contain a small number of functions or a huge number of functions so it is difficult to keep track of a huge number of function calls.

This is where Call Stack comes in.

The Call stack is used to keep track of the functions that are currently being executed by javascript. When a function gets called, it is added to the top of the stack and when the function returns, it is removed from the top of the stack. This process continues till the last function call is done.

Here you can see add function is called and then added to the top of the stack. Once it returns it will be removed from the stack.

Since add function was removed after it returned, the next function (if any) sub gets added on top of the stack. And this process continues until every function call is executed.

Conclusion

Javascript is a powerful language that allows developers to create interactive web applications. Understanding how javascript works can help developers write more efficient and effective code.

Ref: How JavaScript Code is executed? & Call Stack | Namaste JavaScript Ep. 2