What exactly Just in time (JIT) compilation is in JavaScript?

Is JavaScript compiled language or interpreted language or a mix of both?

Don't worry! Take a chill pill 😎

I'll break it down for you, bit by bit.

But first thing first...

Take a deep breath, and follow along.

JavaScript engines use the JIT(just in time) compiler to execute the code.

I know you must be wondering what the hell is JIT and how it works?

Tired

Let me demystify it for you

But before understanding JIT, let's change the topic for a while, and try to understand what compiler and interpreter are and how they work?

Compiler

The source code is converted into machine code once and then gets executed.

Compiler

Pros

  • Suppose we have a loop that runs 40 times, we do not need to translate the same code again and again. The time it saves is huge.
  • The converted code will be more efficient cause we have more time for optimization.

Cons

  • It takes a little bit more time to start up because it has to go through that compilation step at the beginning.

Interpreter

Interpreters are quick. We don’t have to go through that whole compilation step before execution. It just starts translating the first line and then executes it.

Interpreters

Pros

  • Fast start-up times are characteristic of interpreters. That's why browsers used JavaScript interpreters in the beginning.

Cons

  • When you’re running the same code more than once. For example, if you’re in a loop. Then you have to do the same translation over and over and over again.
  • The code will be less efficient than the compiler cause we have less time for optimization.

Just In Time(JIT) compiler

To get rid of the interpreter's inefficiency, "the interpreter keeps retranslating the same code every time it goes through the loop".

In the JIT compiler, we have a new component called a monitor (aka a profiler). That monitor watches the code as it runs and

  • Identify the hot or warm components of the code eg: repetitive code.
  • Transform those components into machine code during run time.
  • Optimize the generated machine code.
  • Hot swap the previous implementation of the code.

Just In Time(JIT) compiler

In short Just in time compiler is nothing but a combination of an interpreter and a compiler.

I hope you found it helpful, and if you have any questions, please let me know.


Feel proud to correct me if I'm wrong:)

Twitter || Linkedin

Did you find this article valuable?

Support Hemendra Khatik by becoming a sponsor. Any amount is appreciated!