X

Chrome Browser JavaScript Runtime

A High-Level Overview of JavaScript Runtime in the Browser


A High-Level Overview of JavaScript Runtime in the Browser
The Javascript code we write is executed in Chrome’s Javascript runtime which consists of the following components:
A V8 JavaScript Engine
Web/Browser APIs
Queues
Event Loop

JavaScript Engine (V8):
The JavaScript Engine is the V8 which is responsible for parsing and executing JavaScript code. It includes a compiler that translates JavaScript code into machine code for faster execution. It consists of a call stack where JavaScript code gets executed and a heap which is nothing but a memory to store all the memory that a JavaScript application needs.

Web/Browser APIs:
Web APIs (Application Programming Interfaces) are functionalities provided by the browser, outside the JavaScript engine, to interact with the browser environment.
Examples of Web APIs include the Document Object Model (DOM) API for manipulating HTML and XML documents, the XMLHttpRequest (XHR) for making HTTP requests, and the Web Audio API for handling audio processing.
These APIs allow JavaScript to interact with and manipulate the browser environment, such as modifying the DOM or making network requests.


Microtask Queue:
Microtasks are tasks that are executed after the completion of the current task and before the next task in the event loop.
Promises, which are part of the ECMAScript standard, introduce microtasks. When a promise is settled (resolved or rejected), its corresponding microtask is queued.
Microtasks have higher priority than regular tasks and are processed before the next tick of the event loop.

Callback/Task Queue:
Queues are where asynchronous tasks wait before they can be executed.
The callback or task queue holds tasks that are pushed to the queue for later execution by the event loop.
Callbacks from asynchronous operations (e.g., timers, user interactions, or I/O operations) are placed in the task queue.
These tasks are processed by the event loop, and their execution depends on the state of the call stack and the presence of microtasks.


Event Loop:

The Event Loop is a fundamental concept in the asynchronous nature of JavaScript in the browser.
The Event Loop continuously checks the message queue for messages and executes them one at a time.
It ensures that the execution of JavaScript code remains non-blocking and asynchronous.

Putting it all together:

When you write JavaScript code, it gets executed by the JavaScript engine (V8).
If your code interacts with the browser environment (DOM manipulation, HTTP requests, etc.), it uses Web APIs.
Asynchronous tasks, like callbacks from these APIs, are handled by the event loop.
Microtasks, introduced by promises, have a higher priority than regular tasks and are processed before the next tick of the event loop.