[JS] How JS works behind the scenes, JS Engine, JS Runtime

Hyodduru ·2021년 12월 6일
0

JavaScript

목록 보기
29/60

강의 출처 : The complete JavaScript Course 2022 - Jonas (Udemy)

섹션 8 How JavaScript Works Behind the Scenes

An High-Level Overview of JavaScript

JavaScript?

A high-level prototype-based object-oriented multi-paradigm interpreted or just in time compiled dynamic single-threaded garbage-collected programming language with first-class functions and a non-blocking event loop concurrency model.

high-level

ex) JS, python
개발자들은 세세한 부분까지 신경쓰지 않아도 된다. 모든 것들이 자동적으로 일어난다.

참고) low level (ex. c) : 개발자들이 리소스들을 수동적으로 관리해야한다.

Garbage-collected

자바스크립트는 자동적으로 컴퓨터 메모리에 있는 사용하지 않는 객체를 제거한다. 우리가 따로 메모리를 청소하지 않아도 된다.

Interpreted or just-in-time compiled

인간이 읽을 수 있는 JS code (abstraction over 0s and 1s)
=> needs to be converted to machine code (compiling)

즉 JS 내에서 compling이 일어난다. (사람의 언어를 기계언어로 바꾸어주고 이를 실행함)

Multi-paradigm

paradigm?

간단하게 프로그래밍 스타일을 의미하며 전체적인 프로그래밍 방식을 말한다.
프로그램은 순차, 분기, 반복, 참조로 구성되어지며 프로그램 개발을 위하여 전략을 수립해야 한다.
위에서 말한 전략은 어떤 언어를 사용할지, 프로그래밍에서 어떤 것을 지양하고, 지양할지 등등 다양한 방법을 수립하게 된다. 여기서 말한 전략에 해당하는 내용들이 프로그래밍 패러다임이다.
대표적인 프로그래밍 패러다임에는 절차적, 객체지향, 함수형 프로그래밍이 존재한다.

An approach and mindset of structuring code, which will direct your coding style and technique.
1. Procedural programming
2. Object-oriented programming(OOP)
3. Functional programming(FP)

대부분의 다른 언어들은 이 셋중 하나만 가지고 있는데 JS는 이 세가지를 다 가지고 있다. => 굉장히 유연한 언어.

Prototype-based object-oriented

ex) Array = Array.prototype.push , Array.prototype.indexOf
Array의 prototype 내에서 push와 indexOf와 같은 method를 가지고 있다.

const arr = [1,2,3];
arr.push(4);
const hasZero = arr.indexOf(0) > -1; 

First-class functions

In a language with first-class functions, functions are simply treated as variables. We can pass them into other functions, and return them from functions.

ex)

const h1 = document.querySelector('h1');
const sth = () =>{
	console.log('hi')}
   
h1.addEventListner('click', sth) 

sth이라는 함수를 다른 함수의 argument로 보낸다.

Dymamic (Dynamically-typed language)

ex)

let x = 23;
let y = 29;
y = 'Jonas';

datatype을 따로 설정해줄 필요가 없음. 변수의 data type이 자동으로 바뀜!

Concurrency Model

How the JavaScript engine handles multiple tasks happening at the same time.

  • why do we need that?
    JS runs in one single thread so it can only do one thing at a time.
  • So what about long-running task?
    Sounds like it would block the single thread. However, we want non-blocking behavior.
  • How to achieve?
    By using an event loop. takes long running tasks, executes them in the 'background' and puts them back in the main thread once they finished.

The JavaScript Engine and Runtime

JS Engine

Program that executes JS code

  • Call Stack : Where our code is executed. (execution context로 이루어져 있음.)
  • Heap : Where objects are stored. (object들이 저장되어 있음)

Computer science side note : compliation vs interpretation

compliation?

전체 코드가 한번에 machine코드로 바뀌고 컴퓨터에 의해 실행될 수 있는 2진법 파일로 적힌다.
Entire code is converted into machine code at once and written to a binary file that can be executed by a computer.

source code -> (step 1 : compilation) -> portable file : machine code -> (step 2 : execution) -> program running

compitation이 지난 후 한참 후에 코드 실행이 진행될 가능성이 있다.

interpretation?

Interpreter runs through the source code and executes it line by line.

source code -> (step 1 : execution line by line) -> program running

code still needs to be converted to machine code

기존의 JS는 interpretation을 이용함. 시간이 compilation에 비해 너무 많이 걸린다는 단점이 있다.

이를 보완하고자 modern JS에서는 Just-in-time(JIT) compilation 이용!

Just-in-time(JIT) compilation?

Entire code is converted into machine code at once, then excuted immediately.

source code -> (step 1 : compilation) -> machine code(not a portable file) -> (step 2 : execution) -> programming running

execution happens immediately

Modern Just-in-time compilation of JS

코드 실행시키는 단계
1. get code
2. (JS Engine 내에서) parsing : read the code. code is parsed into data structure(AST abstract syntax tree). 코드가 하나하나 tree 형태로 정리된다.
3. compilation : compiles to machine code (just-in-time compilation)
4. execution : execute right away! (happens in callstack)
5. optimization : happens during execution. unoptimized codes are automatically converted into optimized codes. => modern engine 빠르게 만든다.

참고사항) parsing, compilation, optimization -> happens in special threads that we can't access from code

The bigger picture : JS Runtime

Runtime in the Browser : container including all the things that we need to use JS
Web APIs : Functionalities provided to the engine, accessible on window object (not part of JS)
Event Loop : Essential for non-blocking concurrency model (callback queue에 있는 아이들 callstack에 가져가서 실행시킴)

참고) JS browser밖에서도 runtime 가능하다. ex) node.js
Web APIs는 browser에서 제공하는 것이므로 쓰이지 않음! 대신 c++bining & thread pool 이 있음.

profile
꾸준히 성장하기🦋 https://hyodduru.tistory.com/ 로 블로그 옮겼습니다

0개의 댓글