How JavaScript Works

 

According to Wikipedia,

 

JavaScript, often abbreviated as JS, is a high-level, interpreted programming language.

 

It is a language which is also characterized as dynamic, weakly typed, prototype-based and multi-paradigm.

  • Easy to grasp syntactically, dynamic, and powerful language for designers/amateur developers
     
  • Originally intended to be a client side language
     
  • Powerful features from the beginning
    • First class functions
    • Prototype based inheritance

The origin

Comparison with other languages

Dynamic typing

Static typing

Interpreted

vs

JIT

vs

AOT

  •  Execute instructions directly, without previously compiling a program into machine language instructions
     
  • JavaScript was originally an interpreted language

Interpreted

  • Longer initialization times (warmup phase)
     
  • Faster in the long run as compiled functions can be reused
     
  •  If it takes 500 ms to interpret a function, and 700 ms to JIT compile it, after JIT compilation, it might take only 100 ms to actually run
     
  • Why was JavaScript not JIT compiled from the start?

JIT compiled

  • Needs compilation before running
     
  • No warmup phase
     
  • Reduced runtime overhead
     
  • Why is JavaScript not AOT compiled?

AOT compiled

  • Parallel execution
     
  • Offloading CPU intensive task to a new thread
     
  • Increases complexity

Multi threaded

  • One thing at a time
     
  • Simple to understand

Single threaded

The JavaScript Engine

Browser

The Call Stack

The Call Stack

The Call Stack

This is exactly how stack traces are constructed when an exception is being thrown 

Bonus tip 💡

You can use console.trace() in any function to print a stack trace

Single call stack means, one task at a time

 

So how do asynchronous callbacks work?

Threading is hidden from you. You can call these async APIs from your code.

Other Web APIs, like AJAX and DOM APIs work in the same way

What the heck is setTimeout(callback, 0)?

Rendering in browser

  • Most of the browsers repaint every 16.66 ms
     
  • Repaints only when needed i.e. there are changes in DOM
     
  • Repaints are queued to be executed
     
  • requestAnimationFrame()

Learn more

Thank you

Made with Slides.com