How JavaScript Works: Behind the Scenes

How JavaScript Works: Behind the Scenes

JavaScript is the world's most misunderstood programming language. Let's try to understand it.

js-me.jpeg

JavaScript Overview

What if I told you that, our lives today are dependent on JavaScript. If you really want to see how much you depend on it, just disable JavaScript in your browser for a day. You'll notice that some web pages load faster than usual, they'll be cleaner, have fewer ads, no pop-ups. But most of the web pages will not work at all, Neither will Netflix, YouTube, WhatsApp Web, Google Maps, and much more. Today, virtually every computing device including iPhones, MacOs, Windows, Linux, Smart TV, Android phones, etc. has installed JavaScript Interpreters on them and is actively used.

There are over 1.8 Billion websites in the world, and JavaScript is used on 95% of them. Today's JavaScript is not only used for web development, here is the list of areas where JavaScript is being used apart from the web.

JavaScript popularity over the years. js-graph.png

Let's start with the broader definition of JavaScript.

JavaScript is a high-level, prototype-based object-oriented, multi-paradigm, interpreted or just-in-time compiled, dynamic, single-threaded, garbage-collected programming language with first-class function and a non-blocking event-loop concurrency model. 🤯🤯

If you are a noob JavaScript developer, this blog post will help you understand why JavaScript is so "weird" compared to other languages.

And if you are a super experienced JavaScript developer, it will give you some fresh insight into JavaScript.

This post is aimed to dig deeper into JavaScript and how it actually works: I thought that by knowing the building block of JavaScript you'll be able to write better code which results in better application.

The JavaScript Engine

jsmeme3.jpg

In simple terms, JavaScript engines are programs that convert JavaScript code into lower-level or machine code. JavaScript engines are typically developed by web browser vendors, and every major browser has one. They follow the ECMAScript standards. These standards define how the JavaScript engine should work and what features it should have. So, we can also call them ECMAScript engines.

JavaScript is usually categorized as interpreted language although it is technically compiled language. Modern JavaScript compilers actually perform Just-in-time Compilation which occurs during run-time.

Google's V8 v8.jpg

V8 from Google is the most used JavaScript engine. It is an open-source project that comes under the Chromium project developed for Google Chrome and Chromium web browsers. The first version of the V8 engine was released at the same time as the first version of Chrome: 2 September 2008. The key innovation in the V8 engine was Just-in-time compilation, which can significantly improve execution times. It is also being used by Node.Js and Deno runtime system.

Chakra chakra.png

Chakra is a JavaScript engine developed by Microsoft for its Microsoft Edge web browser, but Edge was later rebuilt as a Chromium-based browser and thus now uses the V8 engine. The important feature of the engine is that it JIT compiles scripts on a separate CPU core, parallel to the web browser.

SpiderMonkey spider-monkey.png

SpiderMonkey is the code name for the first JavaScript engine, written by Brendan Eich at Netscape Communications, later released as open-source and currently maintained by Mozilla Foundation. It is written in C and C++. It is used in various Mozilla products, including Firefox and is available under MPL2 ( Mozilla public license version 2.0). It is also being used by GNOME Shell for extension support. SpiderMonkey contains an interpreter, several JIT compilers ( TraceMonkey, JagarMonkey, and IonMonkey ), a decompiler, and a garbage collector.

JavaScriptCore safar.jpg

JavaScriptCore is Apple's engine for its Safari browser. It is a framework that provides a JavaScript engine for WebKit implementations. It is originally derived from the KDE JavaScript engine library ( which is a part of the KDE project ).

On June 2, 2008, the Webkit project announced they rewrote JavaScriptCore. WebKit is a browser engine developed by Apple and primarily used in its Safari web browser, and all IOS web browsers. WebKit is also used by BlackBerry browser, PlayStation consoles, the Tizen mobile OS, and a browser included with the Amazon Kindle e-book reader.

JavaScript Runtime Environment

js-runtime.png

JavaScript is a single-threaded language which means that only one set of instructions can be executed at a time. The JavaScript engine works inside an environment, which provides access to built-in libraries and objects that are available to a program so that it can interact with the outside world. An example here might be access to information about the web browser in the script is executing or, a notification about a mouse click.

Note:- The runtime environment in a browser is very different from that of Node.js. But, most of the following concepts are still relevant.

In the context of the browser, this is comprised of the following elements:

  1. The JavaScript Engine
  2. Web APIs
  3. The callback queue
  4. The event loop

The JavaScript Engine

At this part of the article, you already know enough about JavaScript Engine. The purpose of the JavaScript engine is to translate source code that developers write into machine code.

For the purpose of this article, we are going to focus on the V8 engine.

The Heap:- It is a different space for storing data where JavaScript stores Objects and Functions. Unlike the stack, the engine doesn't allocate a fixed amount of memory for these objects. Instead, more space will be allocated as needed ( Allocating memory this way is also called dynamic memory allocation ).

Call Stack:- A call stack is a mechanism for a JavaScript interpreter to keep track of its place in a script. Like, What function is currently being run and what functions are called from within that function, etc.

call-stack.png

  • When a script calls a function, the interpreter adds it to the call stack and then starts carrying out the function.
  • Any functions that are called by that function are added to the call stack further up and run where their calls are reached.
  • When the current function is finished, the interpreter takes it off the stack and resumes executions where it left off in the last code listing.
  • If the stack takes up more space than it has been assigned to it, it results in "Stack Overflow" error.

Web APIs

It is not a part of the JavaScript engine, but they are part of the JavaScript runtime environment provided by the browser. There are a large number of APIs available in modern browsers that allow us to do a wide variety of things. For example, DOM API, Canvas API, Fetch API, etc. If you want to learn about the APIs available in our browser, Then you can refer to MDN Web Docs.

The Callback Queue

Callback queue or message queue contains the list of messages to be processed and their associated call-back functions. The messages are queued in response to external events ( Like response from the click event ). As the external events are web APIs that are not part of the V8 runtime, when the call stack encounters it pushes to another block where it starts to execute and pushes to callback queue when it receives the response or the timer is finished.

Event Loop

Event loop is a simple piece that puts the whole puzzle together. So when the set timeout or click function is called or when pushed onto the stack, after the execution it goes to the callback queue. if the call stack is empty, then it pushes the first processed callback function present in the callback queue to the call stack. Each message is processed completely before any other message is processed.

Thank you for being a part of this blog. I hope, you understood how javascript works behind the scene.🙏

Did you find this article valuable?

Support Shubham Raj by becoming a sponsor. Any amount is appreciated!