Open In App

Is JavaScript Interpreted or Compiled ?

Last Updated : 22 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript is an interpreted language, and to understand this, it’s important to clarify the concepts of interpreters, compilers, and JIT (Just-In-Time) compilers:

  • Interpreter: An Interpreter directly executes instructions written in a programming or scripting language without previously converting them to an object code or machine code.
  • Compiler: A compiler takes an entire program and converts it into object code which is typically stored in a file. The object code is also referred as binary code and can be directly executed by the machine after linking. 
  • JIT compiler: A JIT compiler first converts the whole code to byte code and then uses the compiler at runtime to convert the code into machine-readable code. JIT compiler helps in faster execution.

JavaScript is primarily interpreted, but modern JavaScript engines, like V8 used in Google Chrome, incorporate JIT compilation techniques to improve performance by translating JavaScript code into optimized machine code just before it’s executed. This combination of interpretation and JIT compilation makes JavaScript a versatile and high-performance language for web applications.

How is JavaScript code executed?

The parsing of JavaScript code is done before execution so it looks like a parsed language but the code is converted to binary form before execution. To further understand this concept let us see how this code execution takes place behind the scenes.

  • First, the code is transpiled using babel or any other web pack.
  • This form of code is given to the Engine which converts it to AST(Abstract Syntax Tree).
  • This AST is then converted to the byte code which is understood by the machine. This is an Intermediate Representation(IR) which is further optimized by the JIT compiler.
  • After the optimization, the JS Virtual Machine Executes the code.

Hence we can conclude that JS code is executed in three phases.

Parsing -> Compiling -> Executing

Hence, we can conclude that JavaScript code is initially interpreted before any execution begins

Example: To support this statement we will look at the code example below.

Javascript




console.log("Hello");
for(var i = 0;i<4;i++) {
    console.log(hello);
}


Output: We can see the interpreter behavior in the above code example, here first Hello is printed at the console and then an error is reported. This output strongly supports the fact that JavaScript is an interpreted language.

In general it may look as if JavaScript code is being executed line by line because of the parsing phase but the whole code is compiled at once to convert it to machine-readable code before execution. This shows that JavaScript is a Just-In-Time compiled language that uses an interpreter in its first phase.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads