본문 바로가기

Programming/JavaScript

What is a JavaScript Engine?

a JavaScript Engine is a computer program that executes javascript code.

E.g. V8 Engine

 

JS Engine 항상 이 2개를 포함함

  • CALL STACK: where our code is actually executed using execution context
  • HEAP: where objects are stored e.g. object in memory

Compilation vs. Interpretation

Compilation: Entire code is converted into machine code at once, and written to a binary file that can be executed by a computer.

 

Step 1

Source code -> (Compilation) -> Portable file: machine code

 

Step 2

Portable file: machine code -> (Execution) -> Program running

 

Interpretaiton: interpreter runs through the source code and executes it line by line.

Source code -> (Execution line by line) -> Program running

* Code still needs to be converted to machine code

 

JS는 interpreted language 였음

문제? compile language보다 훨씬 느림 = low performance

 

지금의 JS는 compilation과 interpretation의 속성을 둘다 합친거라 보면 됨

-> Just-in-time (JIT) compilation: Entire code is converted into machine code at once, then executed immediately.

  • compilation과 차이라면 compilation후에 machine code 나옴 but not a portable file
  • execution happens immediately after compilation

= 코드를 한줄 한줄 실행하는 것보다 훨씬 빠름

 

The bigger picture: javascript runtime

Runtime in the browser

  • JS ENGINE (including HEAP, CALL STACK)

-> Container including all the things that we need to use JavaScript (in this case in the browser)

  • WEB APIs (e.g. DOM, Timers, Fetch API ..)

-> Functionalities provided to the engine, accessible on window object

  • CALLBACK QUEUE

which is data structure

-> e.g. callback function from DOM event listener (click, timer, data ...)

 

클릭을 하면 CALLBACK QUEUE에 있던 onClick이 CALL STACK으로 이동해서 실행됨

How? EVENT LOOP을 통해서

=> event loops takes callback function from callback queue and puts them in the call stack so that they can be executed.

 

EVENT LOOP?

Essential for non-blocking concurrency model

 

https://blog.sessionstack.com/how-does-javascript-actually-work-part-1-b0bacc073cf

 

How JavaScript works: an overview of the engine, the runtime, and the call stack

As JavaScript is getting more and more popular, teams are leveraging its support on many levels in their stack - front-end, back-end…

blog.sessionstack.com