V8 Javascript Engine — Under the Hood

Let me teach you some basics of computers. Our computers consists of processors, which when given a command, executes it. But in order to talk to a processor, we need a language

Tom: Oh! Ok I get it now. So Node.js is that language which talks to the processors

No. It isn’t. Processors do not understand high level languages rather you have to provide them with Instruction Sets(Machine Code). But writing machine code isn’t easy. Lets just take a peek

Understood anything? Me neither. There are different types of instruction sets for different types of processors. So the code we write must be converted into these instruction sets for the processor to execute. This conversion must be performed by some process and this is where Javascript engines make their entrance.

A Javascript engine is a program that converts Javascript code into instruction sets that the machine can understand. There are many JS engines created and maintained by technology leaders of the world and the most popular among them is the V8 Javascript Engine developed by Google. World’s famous browser, Google Chrome, runs on top of V8 Javascript engine.

All Hail Our Robot Overloads

ECMAScript

Tom: How does V8 or any other Javascript engine know how to convert javascript to machine code? Are there any standards defining what any piece of javascript code must contain?

Yes, there is. Everybody puts your hands together for ECMAScript. ECMAScript defines the language specification for javascript describing each and every components of javascript, their functionalities, etc. All the javascript engines use ECMAScript specifications to convert javascript code to Machine code.

C++

Tom: Rahul, Weren’t we talking about Javascript? Why are we jumping to C++ now?

Tom, V8 engine is written in C++ and before you question me why is that important, take a look at the screenshot of V8 homepage shown below

As highlighted, V8 can run standalone or can be embedded into any C++ application. So if I write a C++ program, I can embed V8 and process any js code that I write.

V8 also has hooks that I can use in my C++ program to add addition features to Javascript and can expose multiple features for people to code to. Since I am writing C++ code, I can add hell a lot of feature. Javascript was supposed to be browser based language and now with the plethora of library that exists with C++, I can add a lot of new functionality(access file system, db connection, etc) to Javascript.

This is exactly what Node.js does. But in a very larger scale adding features to Javascript which were never expected to be a part of Javascript community.

Tom: Does that mean Node.js is also written in C++

Spot on Tom!!! Node.js is written in C++ and it embeds V8 to convert js to machine code and introduces innumerable features into the Javascript ecosystem.