Skip to content

Commit 593841b

Browse files
Added JavaScript Engine, Google v8 architecture, and the behavior of setTimeout, including concurrency model and execution flow.
1 parent c422fa0 commit 593841b

2 files changed

Lines changed: 117 additions & 0 deletions

File tree

19_JS_Engine_And_ChromeV8.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# CHAPTER 19: JS Engine and Google v8 architecture
2+
3+
#### JS runs literally everywhere from smart watch to robots to browsers because of Javascript Runtime Environment (JRE)
4+
5+
- JRE consists of a JS Engine (Heart of JRE), set of APIs to connect with outside environment, event loop, Callback queue, Microtask queue etc.
6+
- JRE is a container that can run JS code.
7+
8+
- ECMAScript is a governing body of JS. It has set of rules followed by all JS engines like Chakra(Edge), Spidermonkey(Firefox), v8(Chrome)
9+
- JS Engine is **not a machine**. Its software written in low level languages (eg. C++) that takes in hi-level code in JS and spits out low level machine code.
10+
11+
In all languages, code is compiled either with **interpreter** or with **compiler**. JS used to have only interpreter in old times, but now has **both** to compile JS code.
12+
13+
Interpreter : Takes code and executes line by line. Has no idea what will happen in next line. Very fast.
14+
Compiler : Code is compiled and an optimized version of same code is formed, and then executed. More efficient
15+
16+
- Code inside JRE passes through 3 steps : **Parsing, Compilation and Execution**
17+
18+
1. **Parsing** - Code is broken down into tokens. In "let a = 7" -> let, a, =, 7 are all tokens. Also we have a **syntax parser** that takes code and converts it into an **AST (Abstract Syntax Tree)** which is a JSON with all key values like type, start, end, body etc (looks like package.json but for a line of code in JS. Kind of unimportant) (Check out astexplorer.net -> converts line of code into AST)
19+
20+
2. **Compilation** - JS has something called **Just-in-time(JIT) Compilation - uses both interpreter & compiler**. Also compilation and execution both go hand in hand. The AST from previous step goes to interpreter which converts hi-level code to byte code and moves to execeution. While interpreting, compiler also works hand in hand to compile and form optimized code during runtime.
21+
22+
**NOTE:**
23+
24+
Interpreter: Runs code line by line. => Fast
25+
Compiler: compiles whole code at once. => Efficiency
26+
27+
JavaScript can be complied or interpreted language, everything depends on JS Engine.(So in the begi nning when Brendan Eich created JS, it was meant to be an interpreted language because the browser won't wait for the code to compile and then run. But now most of the modern browser/JS engine uses both compiler and interpreter. So, now it all depends on JS Engine whether it is purely interpreted or Just in compiled.)
28+
29+
3. **Execution** - Needs 2 components ie. Memory heap(place where all memory is stored) and Call Stack. There is also a _garbage collector._ It uses an algo called **Mark and Sweep**.
30+
31+
Companies use different JS engines and each try to make theirs the best.
32+
33+
- v8 of Google has Interpreter called _Ignition_, a compiler called _Turbo Fan_ and garbage collector called _Orinoco_
34+
35+
---
36+
37+
<br><br>
38+
39+
<p align="left">
40+
<a href="./18_Async_And_EventLoops.md"><b>‹ GO TO PREVIOUS</b></a>
41+
</p>
42+
43+
<p align="right">
44+
<a href="./20_setTimeout().md"><b>GO TO NEXT ›</b></a>
45+
</p>
46+
47+
---

20_setTimeout().md

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# Chapter 20: Trust Issues with setTimeout()
2+
3+
```javascript
4+
console.log("Start");
5+
6+
setTimeout(function cb() {
7+
console.log("Callback");
8+
}, 5000);
9+
10+
console.log("End");
11+
```
12+
13+
`setTimeout` sometimes does not exactly guarantee that the callback method will be called exactly after 5s.
14+
Maybe 6,7 or even 10! It all depends on callstack
15+
16+
While execution of program
17+
18+
- First GEC is created and pushed in callstack.
19+
- Start is printed in console
20+
- When `setTimeout` is seen, callback method is registered into webapi's env. And timer is attached to it and started. `cb` waits for its turn to be execeuted once timer expires.
21+
- But JS waits for none. Goes to next line.
22+
- End is printed in console.
23+
- After "End" suppose we have 1 million lines of code that runs for 10 sec(say). So GEC won't pop out of stack. It runs all the code for 10 sec.
24+
- But in the background, the timer runs for 5s. While callstack runs the 1M line of code, this timer has already expired and `cb` fun has been pushed to Callback queue.
25+
- Event loop keeps checking if callstack is empty or not. But here GEC is still in stack so `cb` can't be popped from callback Queue and pushed to CallStack.
26+
- **Though `setTimeout` is only for 5s, it waits for 10s until callstack is empty before it can execute**(When GEC popped after 10sec, `cb()` is pushed into call stack and **immediately executed** (Whatever is pushed to callstack is executed instantly))
27+
- This is called as the **Concurrency model of JS**. This is the logic behind `setTimeout`'s trust issues
28+
29+
### The First rule of JavaScript
30+
31+
- **Do not block the main thread** (as JS is a single threaded(only 1 callstack) language)
32+
33+
- This raises a question. _Why not add more call stacks and make it multithreaded?_
34+
- JS is a synchronous single threaded language. And thats its beauty. With just 1 thread it runs all pieces of code there. It becomes kind of an interpreter language, and runs code very fast inside browser (no need to wait for code to be compiled) (JIT - Just in time compilation). And there are still ways to do async operations as well.
35+
36+
### Now what if the timeout = 0sec
37+
38+
```javascript
39+
console.log("Start");
40+
41+
setTimeout(function cb() {
42+
console.log("Callback");
43+
}, 0);
44+
45+
console.log("End");
46+
```
47+
48+
- Even though `timer = 0s`, the `cb()` has to go through the queue. Registers calback in webapi's env , moves to callback queue, and execute once callstack is empty
49+
50+
Start
51+
52+
End
53+
54+
Callback
55+
56+
- This method of putting `timer = 0`, can be used to defer a less imp fun by a little so the more important fun (here printing "End") can take place
57+
58+
---
59+
60+
<br><br>
61+
62+
<p align="left">
63+
<a href="./19_JS_Engine_And_ChromeV8.md"><b>‹ GO TO PREVIOUS</b></a>
64+
</p>
65+
66+
<p align="right">
67+
<a href="./21_Higher_Order_Functions_And_Functional_Programming.md"><b>GO TO NEXT ›</b></a>
68+
</p>
69+
70+
---

0 commit comments

Comments
 (0)