Is JavaScript Interpreted or Compiled ?

JavaScript is an interpreted language. To understand this better, let’s look at interpreters, compilers, and JIT (Just-In-Time) compilers:

1. Interpreter: An interpreter runs instructions directly from the programming language without changing them into machine code first.

2. Compiler: A compiler changes the entire program into object code (or binary code) and saves it. This code can then be run by the machine.

3. JIT Compiler: A JIT compiler converts code into byte code first. Then, at runtime, it changes the byte code into machine-readable code, which makes the program run faster.

JavaScript is mainly interpreted, but modern JavaScript engines, like V8 in Google Chrome, use JIT (Just-In-Time) compilation to boost performance. They convert JavaScript code into optimized machine code right before it runs. This mix of interpretation and JIT compilation makes JavaScript fast and versatile 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.

It might seem like JavaScript runs code line by line, but that’s due to the parsing phase. In reality, the entire code is compiled into machine-readable code before it runs. This means JavaScript is a Just-In-Time (JIT) compiled language that uses an interpreter first.