Story

Unfortunately, your operating system does not understand JavaScript because it is a high-level language. So, V8 is a JavaScript engine (lives in Chrome, Chromium-based browsers, and Node.js) built with C++ that translates JS code into machine code so the OS and CPU can understand.

And the translator does not translate all at once; instead, it translates bit by bit. This is called JIT (Just In Time) compilation. Once translated, the instructions are stored in a big storage called the 'Heap', which is like a big warehouse. The Call Stack has a small space to store and it only keeps track of what part of the compilation is happening.

After the translator has done its job and everything is organized, the CPU reads the translated instructions. :) Isn’t it amazing how beautifully JavaScript works behind the scenes to make everything run so smoothly?

How JavaScript Runs Behind the Scenes

Let’s break down the story into a technical explanation:

  • High-Level Language: JavaScript is a high-level language, meaning it is easy for humans to read but computers (OS/CPU) cannot understand it directly.
  • JavaScript Engine: V8 (used in Chrome, Chromium, and Node.js) is built with C++ and acts as a translator. It converts JS code into machine code that the CPU can execute.
  • JIT Compilation: V8 does not translate the entire code at once. Instead, it compiles code just in time as needed, making execution faster and more efficient.
  • Heap & Call Stack:
    • The Heap is a large memory area where objects and data are stored.
    • The Call Stack is a small memory space that keeps track of function calls and execution order.
  • CPU Execution: Once the code is translated and organized, the CPU reads and executes the instructions.

Key Takeaways

  • JavaScript is executed in a single-threaded manner but can handle asynchronous tasks efficiently with the help of event loops.
  • V8 engine optimizes code during runtime for better performance using techniques like hidden classes and inline caching.
  • The combination of the Heap, Call Stack, and JIT compilation ensures JS runs smoothly and efficiently even in large applications.
  • Understanding this flow helps developers write optimized and efficient JavaScript code, knowing how it will be processed by the engine behind the scenes.