Is JavaScript compiled or interpreted?

Is it a bird, is it a plane. Nope, it's JIT!

Let us first understand what is an Interpreted language and how is it different from a compiled language.

In case of a compiled language, our written code is processed by a piece of program called compiler and it generates a portable file written in machine language (binary code) which can be executed later at any point of time. In case of an Interpreted language, no binary code file is generated. Our written code is processed line-by-line. This means, the interpreter takes one line, converts it into machine code and then executes it. Then, it moves to the next line and repeats this process. If an error occurs at any line, the whole process stops right there.

So, these are very clear differences between a compiler and an interpreter. Now the big question comes. What kind of programming language is JavaScript? Is it compiled or interpreted?

None!

JavaScript uses a mix of compilation and interpretation. It is called Just In Time (JIT) compilation. In this process, the entire code is converted into machine code at once like compilation. However, unlike compiler, it does not generate any file which can be executed at a later point in time. The generated machine code has to immediately executed by the JavaScript engine.

JIT compilation happens inside modern JS engine in 4 steps:

1. Parsing: The whole JS code is parsed, and an AST (Abstract Syntax Tree) is created. AST is human readable Tree like structure which contains details about the machine code to be created.

2. Compilation: That AST is converted to Machine code via compilation.

3. Execution: After compilation, the resulting machine code is executed right away by the JavaScript engine inside Execution Context. But this code is not well-optimized. It is executed so that things can start without any delay.

4. Optimization: Then in the background, in a separate hidden thread, this code is optimized and recompiled. After that, the original code is replaced with new optimized version without stopping execution (like hot swapping). This is repeatedly done if required. This special thread of optimization is separate from main thread of execution and is not accessible through our code. it is hidden by JS engine. This process makes modern JS engines like V8 so fast.

I hope, now it is clear that JavaScript is neither a compiled language nor an interpreted language. It is Just In Time compiled.

Did you find this article valuable?

Support Ujjawal Chatterjee by becoming a sponsor. Any amount is appreciated!