JavaScript Series Part 1: Is JavaScript a Compiled or Interpreted Language?

JavaScript Series Part 1: Is JavaScript a Compiled or Interpreted Language?

JavaScript is an object-oriented scripting language where the code is run in the browser.

Features of JavaScript

  1. JavaScript is a lightweight, interpreted programming language

  2. JavaScript is an open and cross-platform scripting language

How Engines Work

The engine embedded in a browser reads "parses" the script file then converts and "compiles" the script to a machine language which eventually runs very fast. During the process, the engine applies optimizations at each step of the process.

How does JavaScript work?

How does the browser understand a JavaScript file?

Written JavaScript file is handled by a JavaScript Engine. Different browsers have different JavaScript Engines, for example:

  1. V8 in Chrome and Opera

  2. SpiderMonkey in Mozilla Firefox, etc.

V8 Engine converts JavaScript code into a binary for a computer to understand. Some Components of the V8 Engine include:

  1. Memory Heap for memory allocation, and

  2. Call Stack to keep track of where the code execution is at.

So, how do we get to machine code?

To get to machine code, a JavaScript file will have to be either compiled or interpreted. For compilation, the entire source code is converted to machine code at once while with interpretation, there is an interpreter that runs through the source code and executes it line by line.

At this point, it is worth noting that interpreted languages are much slower than compiled languages.

Is JavaScript Compiled or Interpreted?

Modern JavaScript engine now uses a mix of compilation and interpretation which is referred to as Just In Time (JIT) compilation. The compiler and interpreter are not sufficient for efficiency, which is why JIT comes into the picture.

JIT works by first converting a whole code into a byte after which it used the compiler at runtime to convert the code into machine-readable code.

In summary, JavaScript is a collection of compilers as well as interpreters known as JIT. JIT compilation is a method of improving code performance as it decides the most frequently used code, then compiles it to machine code.