Skip to content

Commit 8541b70

Browse files
Hachondeorosumn2u
authored andcommitted
Add "JavaScript behind the scenes" section with key concepts
Introduce new comprehensive documentation covering foundational concepts of JavaScript's internal mechanisms. Key topics include Call Stack, Engine, and Event Loop, providing a deeper understanding for writing efficient code.
1 parent ef95c5b commit 8541b70

File tree

5 files changed

+350
-0
lines changed

5 files changed

+350
-0
lines changed

en/SUMMARY.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,10 @@
133133
- [Velocity JS](animation-resources/velocityjs.md)
134134
- [React Spring](animation-resources/react-spring.md)
135135
- [Framer Motion](animation-resources/framer-motion.md)
136+
- [JavaScript behind the scenes](behind-scenes/README.md)
137+
- [Call stack](behind-scenes/call-stack.md)
138+
- [Engine](behind-scenes/engine.md)
139+
- [Event loop](behind-scenes/event-loop.md)
136140
- [References](References.md)
137141
- [Resources](resources.md)
138142
- [Credits](Credits.md)

en/behind-scenes/README.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
---
2+
layout: editorial
3+
chapter: 27
4+
pageNumber: 256
5+
description: JavaScript behind the scenes.
6+
---
7+
8+
## JavaScript Behind the Scenes
9+
10+
JavaScript is a versatile language that runs in various environments, including browsers and servers. Understanding how
11+
JavaScript works behind the scenes can help you write more efficient and effective code. This guide covers key concepts
12+
such as the JavaScript engine, execution context, call stack, memory heap, runtime environment, and event loop.
13+
14+
### JavaScript Engine
15+
16+
A JavaScript engine is a program or interpreter that executes JavaScript code. Popular engines like V8 (used in Google
17+
Chrome and Node.js), SpiderMonkey (used in Firefox), and JavaScriptCore (used in Safari) parse the code into an Abstract
18+
Syntax Tree (AST), compile it into bytecode or machine code, and then execute it.
19+
20+
### Execution Context
21+
22+
An execution context is an environment where JavaScript code is evaluated and executed. There are three types: global,
23+
function, and eval. Each context has a creation phase, where variables, functions, and the `this` keyword are created,
24+
and an execution phase, where the code is executed line by line.
25+
26+
### Call Stack
27+
28+
The call stack is a data structure that keeps track of function calls in a Last-In, First-Out (LIFO) manner. It helps
29+
the JavaScript engine manage the execution of multiple functions by pushing and popping function calls as they are
30+
invoked and completed.
31+
32+
### Memory Heap
33+
34+
The memory heap is a region in memory where objects are stored. JavaScript uses garbage collection to manage memory,
35+
automatically freeing up memory that is no longer in use, thus preventing memory leaks and optimizing performance.
36+
37+
### Runtime Environment
38+
39+
The runtime environment provides the necessary resources for JavaScript to execute. In a browser, this includes the
40+
Document Object Model (DOM), Web APIs, and the JavaScript engine. In Node.js, it includes the file system, HTTP module,
41+
and other Node.js-specific APIs.
42+
43+
### Event Loop
44+
45+
The event loop allows JavaScript to perform non-blocking operations by offloading tasks to the system kernel whenever
46+
possible. It continuously checks the call stack and processes the callback queue, enabling asynchronous programming and
47+
efficient execution of code.

en/behind-scenes/call-stack.md

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
---
2+
chapter: 27
3+
pageNumber: 257
4+
description: Understanding Call Stacks in JavaScript
5+
---
6+
7+
8+
## Understanding Call Stacks in JavaScript
9+
10+
In JavaScript, a Call Stack is a data structure that uses the Last-In, First-Out (LIFO) principle to temporarily store and manage function invocation (call).
11+
12+
### What is a Call Stack?
13+
14+
A call stack is responsible for keeping track of function calls in your code. The call stack helps the JavaScript interpreter to keep track of what function is currently being run and what functions are called from within that function, and so on.
15+
16+
When a script calls a function, JavaScript's interpreter adds that function to the call stack and then starts carrying out the function. Any functions that are called by that function are added to the call stack further up, and run where their calls are reached.
17+
18+
When the current function is finished, the interpreter takes it off the stack and resumes execution where it left off in the last line of code that was run.
19+
20+
### Example of a Call Stack
21+
22+
Here's a basic example to understand how a call stack works:
23+
24+
```javascript
25+
function firstFunction() {
26+
console.log("First function is called.");
27+
secondFunction();
28+
console.log("First function is done.");
29+
}
30+
31+
function secondFunction() {
32+
console.log("Second function is called.");
33+
thirdFunction();
34+
console.log("Second function is done.");
35+
}
36+
37+
function thirdFunction() {
38+
console.log("Third function is called.");
39+
}
40+
41+
firstFunction();
42+
```
43+
44+
**Output:**
45+
```
46+
First function is called.
47+
Second function is called.
48+
Third function is called.
49+
Second function is done.
50+
First function is done.
51+
```
52+
53+
### How the Call Stack Works
54+
55+
1. When `firstFunction` is called, it is added to the call stack.
56+
2. Inside `firstFunction`, `secondFunction` is called, so it is added to the call stack.
57+
3. Inside `secondFunction`, `thirdFunction` is called, so it is added to the call stack.
58+
4. `thirdFunction` completes and is removed from the call stack.
59+
5. `secondFunction` resumes, completes, and is removed from the call stack.
60+
6. `firstFunction` resumes, completes, and is removed from the call stack.
61+
62+
### Stack Overflow
63+
64+
A stack overflow occurs when there are too many function calls in the call stack. This can happen with recursive functions that do not have a base case to stop the recursion.
65+
66+
```javascript
67+
function recursiveFunction() {
68+
recursiveFunction();
69+
}
70+
71+
recursiveFunction();
72+
```
73+
74+
This will result in a "Maximum call stack size exceeded" error.
75+

en/behind-scenes/engine.md

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
---
2+
chapter: 27
3+
pageNumber: 258
4+
description: Understanding JavaScript Engines and how they execute JavaScript code.
5+
---
6+
7+
## Understanding JavaScript Engines
8+
9+
A JavaScript engine is a program or an interpreter that executes JavaScript code. The most well-known JavaScript engines are V8 (used in Google Chrome and Node.js), SpiderMonkey (used in Firefox), and JavaScriptCore (used in Safari).
10+
11+
### How JavaScript Engines Work
12+
13+
JavaScript engines perform several key tasks to execute JavaScript code efficiently:
14+
15+
1. **Parsing**: The engine parses the JavaScript code into an Abstract Syntax Tree (AST).
16+
2. **Compilation**: The AST is then compiled into bytecode or machine code.
17+
3. **Execution**: The compiled code is executed by the engine.
18+
19+
### Example of JavaScript Engine Workflow
20+
21+
Here's a simple example to illustrate the workflow of a JavaScript engine:
22+
23+
```javascript
24+
function add(a, b) {
25+
return a + b;
26+
}
27+
28+
console.log(add(2, 3)); // Output: 5
29+
```
30+
31+
### Parsing
32+
33+
The engine first parses the code into an AST. For the above code, the AST might look something like this:
34+
35+
```
36+
Program
37+
├── FunctionDeclaration (add)
38+
│ ├── Identifier (a)
39+
│ ├── Identifier (b)
40+
│ └── BlockStatement
41+
│ └── ReturnStatement
42+
│ └── BinaryExpression (+)
43+
│ ├── Identifier (a)
44+
│ └── Identifier (b)
45+
└── ExpressionStatement
46+
└── CallExpression (console.log)
47+
└── CallExpression (add)
48+
├── Literal (2)
49+
└── Literal (3)
50+
```
51+
52+
### Compilation
53+
54+
The AST is then compiled into bytecode or machine code. This step involves optimizations to improve performance.
55+
56+
### Execution
57+
58+
The compiled code is executed by the engine. In this case, the `add` function is called with arguments `2` and `3`, and the result `5` is logged to the console.
59+
60+
### Just-In-Time (JIT) Compilation
61+
62+
Modern JavaScript engines use Just-In-Time (JIT) compilation to improve performance. JIT compilation involves compiling code at runtime, rather than before execution. This allows the engine to optimize the code based on actual usage patterns.
63+
64+
### Example of JIT Compilation
65+
66+
```javascript
67+
function multiply(a, b) {
68+
return a * b;
69+
}
70+
71+
for (let i = 0; i < 1000000; i++) {
72+
multiply(2, 3);
73+
}
74+
```
75+
76+
In this example, the `multiply` function is called repeatedly. A JIT compiler can optimize the function after detecting that it is a hot function (i.e., frequently called).
77+
78+
### Garbage Collection
79+
80+
JavaScript engines also include garbage collectors to manage memory. The garbage collector automatically frees up memory that is no longer in use, preventing memory leaks.
81+
82+
### Example of Garbage Collection
83+
84+
```javascript
85+
function createObject() {
86+
return { name: "Object" };
87+
}
88+
89+
let obj = createObject();
90+
obj = null; // The object is now eligible for garbage collection
91+
```
92+
In this example, the object created by `createObject` is eligible for garbage collection after `obj` is set to `null`.

en/behind-scenes/event-loop.md

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
---
2+
chapter: 27
3+
pageNumber: 259
4+
description: Understanding the Event Loop in JavaScript.
5+
---
6+
7+
## Understanding the Event Loop in JavaScript
8+
9+
The event loop is a fundamental concept in JavaScript that allows for asynchronous programming. It is responsible for executing code, collecting and processing events, and executing queued sub-tasks.
10+
11+
### How the Event Loop Works
12+
13+
JavaScript is single-threaded, meaning it can execute one piece of code at a time. The event loop allows JavaScript to perform non-blocking operations by offloading operations to the system kernel whenever possible.
14+
15+
### Components of the Event Loop
16+
17+
1. **Call Stack**: The call stack is where the JavaScript engine keeps track of function calls.
18+
2. **Web APIs**: These are provided by the browser (or Node.js) and include things like `setTimeout`, `DOM events`, and `HTTP requests`.
19+
3. **Callback Queue**: This is where functions are queued up to be executed after the call stack is clear.
20+
4. **Event Loop**: The event loop continuously checks the call stack to see if it's empty. If it is, it takes the first event from the callback queue and pushes it to the call stack.
21+
22+
### Example of the Event Loop
23+
24+
Here's a simple example to illustrate how the event loop works:
25+
26+
```javascript
27+
console.log("Start");
28+
29+
setTimeout(() => {
30+
console.log("Timeout");
31+
}, 0);
32+
33+
console.log("End");
34+
```
35+
36+
**Output:**
37+
```
38+
Start
39+
End
40+
Timeout
41+
```
42+
43+
### Explanation
44+
45+
1. `console.log("Start")` is executed and "Start" is printed.
46+
2. `setTimeout` is called, and the callback is sent to the Web API. The main thread continues.
47+
3. `console.log("End")` is executed and "End" is printed.
48+
4. The event loop checks the call stack and finds it empty. It then pushes the `setTimeout` callback to the call stack.
49+
5. The `setTimeout` callback is executed and "Timeout" is printed.
50+
51+
### Event Loop in Action
52+
53+
Here's a more complex example to demonstrate the event loop in action:
54+
55+
```javascript
56+
console.log("Start");
57+
58+
setTimeout(() => {
59+
console.log("Timeout 1");
60+
}, 1000);
61+
62+
setTimeout(() => {
63+
console.log("Timeout 2");
64+
}, 0);
65+
66+
Promise.resolve().then(() => {
67+
console.log("Promise");
68+
});
69+
70+
console.log("End");
71+
```
72+
73+
**Output:**
74+
```
75+
Start
76+
End
77+
Promise
78+
Timeout 2
79+
Timeout 1
80+
```
81+
82+
### Explanation
83+
84+
1. `console.log("Start")` is executed and "Start" is printed.
85+
2. `setTimeout` with 1000ms delay is called and the callback is sent to the Web API.
86+
3. `setTimeout` with 0ms delay is called and the callback is sent to the Web API.
87+
4. `Promise.resolve().then` is called and the callback is sent to the microtask queue.
88+
5. `console.log("End")` is executed and "End" is printed.
89+
6. The event loop checks the call stack and finds it empty. It then processes the microtask queue first, executing the `Promise` callback and printing "Promise".
90+
7. The event loop then processes the callback queue, executing the `setTimeout` with 0ms delay and printing "Timeout 2".
91+
8. Finally, the `setTimeout` with 1000ms delay is executed and "Timeout 1" is printed.
92+
93+
### Microtasks vs Macrotasks
94+
95+
Microtasks (e.g., Promises) have higher priority than macrotasks (e.g., `setTimeout`). The event loop processes all microtasks before moving on to the next macrotask.
96+
97+
### Example of Microtasks and Macrotasks
98+
99+
```javascript
100+
console.log("Start");
101+
102+
setTimeout(() => {
103+
console.log("Timeout");
104+
}, 0);
105+
106+
Promise.resolve().then(() => {
107+
console.log("Promise 1");
108+
}).then(() => {
109+
console.log("Promise 2");
110+
});
111+
112+
console.log("End");
113+
```
114+
115+
**Output:**
116+
```
117+
Start
118+
End
119+
Promise 1
120+
Promise 2
121+
Timeout
122+
```
123+
124+
### Explanation
125+
126+
1. `console.log("Start")` is executed and "Start" is printed.
127+
2. `setTimeout` is called and the callback is sent to the Web API.
128+
3. `Promise.resolve().then` is called and the callback is sent to the microtask queue.
129+
4. `console.log("End")` is executed and "End" is printed.
130+
5. The event loop processes the microtask queue, executing the `Promise` callbacks and printing "Promise 1" and "Promise 2".
131+
6. The event loop then processes the callback queue, executing the `setTimeout` callback and printing "Timeout".
132+

0 commit comments

Comments
 (0)