Skip to content

Commit 9911647

Browse files
Hachondeorosumn2u
andauthored
Added more chapters to Behind scenes (#219)
* 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. * Add new chapters on Execution Context, Memory Heap, and Runtime Environment Introduced detailed chapters to explain fundamental JavaScript concepts. Includes descriptions and code examples for understanding execution context, memory heap, and runtime environment. Updated SUMMARY.md to reflect these additions. --------- Co-authored-by: Suman Kunwar <[email protected]>
1 parent f52a00b commit 9911647

File tree

4 files changed

+328
-0
lines changed

4 files changed

+328
-0
lines changed

en/SUMMARY.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,9 @@
137137
- [Call Stack](behind-scenes/call-stack.md)
138138
- [Engine](behind-scenes/engine.md)
139139
- [Event Loop](behind-scenes/event-loop.md)
140+
- [Execution Context](behind-scenes/execution-context.md)
141+
- [Memory Heap](behind-scenes/memory-heap.md)
142+
- [Runtime Environment](behind-scenes/runtime-environment.md)
140143
- [References](References.md)
141144
- [Resources](resources.md)
142145
- [Credits](Credits.md)
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
---
2+
chapter: 27
3+
pageNumber: 260
4+
description: Understanding Execution Context in JavaScript.
5+
---
6+
7+
## Understanding Execution Context in JavaScript
8+
9+
In JavaScript, an execution context is an environment where the code is evaluated and executed. It is a fundamental concept that helps manage the scope and behavior of variables and functions.
10+
11+
### Types of Execution Context
12+
13+
There are three main types of execution contexts in JavaScript:
14+
15+
1. **Global Execution Context**: This is the default context where the code starts execution. It creates a global object (e.g., `window` in browsers) and sets up the global scope.
16+
2. **Function Execution Context**: Created whenever a function is invoked. Each function has its own execution context.
17+
3. **Eval Execution Context**: Created when code is executed inside the `eval` function.
18+
19+
### Phases of Execution Context
20+
21+
Each execution context goes through two phases:
22+
23+
1. **Creation Phase**: In this phase, the JavaScript engine sets up the environment for the code to be executed. It involves:
24+
- Creating the `this` binding.
25+
- Setting up the scope chain.
26+
- Creating the variable object (variables, functions, and arguments).
27+
28+
2. **Execution Phase**: In this phase, the JavaScript engine executes the code line by line.
29+
30+
### Example of Execution Context
31+
32+
Here's an example to illustrate how execution contexts work:
33+
34+
```javascript
35+
var globalVar = "I am a global variable";
36+
37+
function outerFunction() {
38+
var outerVar = "I am an outer variable";
39+
40+
function innerFunction() {
41+
var innerVar = "I am an inner variable";
42+
console.log(globalVar); // Accesses global variable
43+
console.log(outerVar); // Accesses outer variable
44+
console.log(innerVar); // Accesses inner variable
45+
}
46+
47+
innerFunction();
48+
}
49+
50+
outerFunction();
51+
```
52+
53+
**Output:**
54+
```
55+
I am a global variable
56+
I am an outer variable
57+
I am an inner variable
58+
```
59+
60+
### Explanation
61+
62+
1. **Global Execution Context**:
63+
- `globalVar` is created and assigned the value "I am a global variable".
64+
- `outerFunction` is created and stored in memory.
65+
66+
2. **Function Execution Context (outerFunction)**:
67+
- `outerVar` is created and assigned the value "I am an outer variable".
68+
- `innerFunction` is created and stored in memory.
69+
70+
3. **Function Execution Context (innerFunction)**:
71+
- `innerVar` is created and assigned the value "I am an inner variable".
72+
- The `console.log` statements access variables from their respective scopes.
73+
74+
### Scope Chain and Lexical Environment
75+
76+
The scope chain is a list of all the variable objects that the currently executing code has access to. The lexical environment is the environment in which the code is written, and it determines the scope chain.
77+
78+
### Example of Scope Chain
79+
80+
```javascript
81+
var a = 10;
82+
83+
function foo() {
84+
var b = 20;
85+
86+
function bar() {
87+
var c = 30;
88+
console.log(a + b + c); // Accesses variables from all scopes
89+
}
90+
91+
bar();
92+
}
93+
94+
foo();
95+
```
96+
97+
**Output:**
98+
```
99+
60
100+
```
101+
102+
### Explanation
103+
104+
1. **Global Scope**: Contains `a`.
105+
2. **Function Scope (foo)**: Contains `b` and has access to `a`.
106+
3. **Function Scope (bar)**: Contains `c` and has access to `a` and `b`.
107+
108+
### Hoisting
109+
110+
Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their containing scope during the creation phase.
111+
112+
### Example of Hoisting
113+
114+
```javascript
115+
console.log(hoistedVar); // Output: undefined
116+
var hoistedVar = "I am hoisted";
117+
118+
hoistedFunction(); // Output: I am a hoisted function
119+
function hoistedFunction() {
120+
console.log("I am a hoisted function");
121+
}
122+
```
123+
124+
### Explanation
125+
126+
- `hoistedVar` is declared but not initialized during the creation phase, so it is `undefined` when accessed.
127+
- `hoistedFunction` is fully hoisted and can be called before its declaration.

en/behind-scenes/memory-heap.md

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
---
2+
chapter: 27
3+
pageNumber: 261
4+
description: Understanding Memory Heap in JavaScript.
5+
---
6+
7+
## Understanding Memory Heap in JavaScript
8+
9+
In JavaScript, memory management is crucial for ensuring efficient and smooth performance of applications. The memory heap is a region in memory where objects, strings, and closures are stored. It is managed by the JavaScript engine's garbage collector.
10+
11+
### What is a Memory Heap?
12+
13+
The memory heap is an area of pre-reserved computer memory that a program can use to store data in some variable amount. Unlike the stack, which is used for static memory allocation, the heap is used for dynamic memory allocation.
14+
15+
### How Memory Heap Works
16+
17+
When you create objects or variables in JavaScript, they are allocated in the memory heap. The JavaScript engine's garbage collector periodically scans the heap to identify and reclaim memory that is no longer in use.
18+
19+
### Example of Memory Allocation
20+
21+
Here's an example to illustrate how memory is allocated in the heap:
22+
23+
```javascript
24+
let obj = {
25+
name: "John",
26+
age: 30
27+
};
28+
29+
let arr = [1, 2, 3, 4, 5];
30+
```
31+
32+
In this example, the object `obj` and the array `arr` are allocated in the memory heap.
33+
34+
### Garbage Collection
35+
36+
JavaScript uses an automatic garbage collection mechanism to manage memory. The garbage collector identifies objects that are no longer reachable and reclaims their memory.
37+
38+
### Example of Garbage Collection
39+
40+
Consider the following example:
41+
42+
```javascript
43+
function createUser() {
44+
let user = {
45+
name: "Alice",
46+
age: 25
47+
};
48+
return user;
49+
}
50+
51+
let user1 = createUser();
52+
let user2 = createUser();
53+
user1 = null; // The object referenced by user1 is now eligible for garbage collection
54+
```
55+
56+
In this example, when `user1` is set to `null`, the object it referenced becomes eligible for garbage collection because it is no longer reachable.
57+
58+
### Memory Leaks
59+
60+
Memory leaks occur when memory that is no longer needed is not released. This can happen if references to objects are unintentionally retained.
61+
62+
### Example of Memory Leak
63+
64+
Here's an example of a memory leak:
65+
66+
```javascript
67+
let arr = [];
68+
function addElement() {
69+
arr.push(new Array(1000000).join('x'));
70+
}
71+
72+
setInterval(addElement, 1000); // This will cause a memory leak as the array keeps growing
73+
```
74+
75+
In this example, the `arr` array keeps growing because new elements are continuously added without being removed, leading to a memory leak.
76+
77+
### Best Practices for Memory Management
78+
79+
1. **Avoid Global Variables**: Minimize the use of global variables to reduce the risk of memory leaks.
80+
2. **Use `let` and `const`**: Prefer `let` and `const` over `var` to limit the scope of variables.
81+
3. **Clean Up References**: Explicitly set references to `null` when they are no longer needed.
82+
4. **Use Closures Wisely**: Be cautious with closures as they can retain references to outer variables.
83+
84+
### Conclusion
85+
86+
Understanding how the memory heap works in JavaScript is essential for writing efficient and performant code. By following best practices and being mindful of memory allocation and garbage collection, you can avoid common pitfalls such as memory leaks.
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
---
2+
chapter: 27
3+
pageNumber: 262
4+
description: Understanding Runtime Environment in JavaScript.
5+
---
6+
7+
## Understanding Runtime Environment in JavaScript
8+
9+
The runtime environment in JavaScript is the context in which your code is executed. It includes the JavaScript engine, the call stack, the memory heap, and the APIs provided by the environment (such as the browser or Node.js).
10+
11+
### JavaScript Engine
12+
13+
The JavaScript engine is responsible for executing your code. Popular engines include V8 (used in Chrome and Node.js), SpiderMonkey (used in Firefox), and JavaScriptCore (used in Safari).
14+
15+
### Call Stack
16+
17+
The call stack is a data structure that keeps track of function calls. When a function is called, it is added to the top of the stack. When the function returns, it is removed from the stack.
18+
19+
### Example of Call Stack
20+
21+
```javascript
22+
function first() {
23+
console.log("First function");
24+
second();
25+
}
26+
27+
function second() {
28+
console.log("Second function");
29+
third();
30+
}
31+
32+
function third() {
33+
console.log("Third function");
34+
}
35+
36+
first();
37+
```
38+
39+
**Output:**
40+
```
41+
First function
42+
Second function
43+
Third function
44+
```
45+
46+
### Memory Heap
47+
48+
The memory heap is where objects, strings, and closures are stored. It is managed by the garbage collector, which reclaims memory that is no longer in use.
49+
50+
### Example of Memory Allocation
51+
52+
```javascript
53+
let obj = {
54+
name: "John",
55+
age: 30
56+
};
57+
58+
let arr = [1, 2, 3, 4, 5];
59+
```
60+
61+
### Event Loop
62+
63+
The event loop is responsible for handling asynchronous operations. It continuously checks the call stack and the task queue, executing tasks from the queue when the stack is empty.
64+
65+
### Example of Event Loop
66+
67+
```javascript
68+
console.log("Start");
69+
70+
setTimeout(() => {
71+
console.log("Timeout");
72+
}, 0);
73+
74+
console.log("End");
75+
```
76+
77+
**Output:**
78+
```
79+
Start
80+
End
81+
Timeout
82+
```
83+
84+
### APIs Provided by the Environment
85+
86+
The runtime environment provides various APIs that you can use in your code. In a browser, these include the DOM, fetch, and setTimeout. In Node.js, these include file system operations, HTTP requests, and more.
87+
88+
### Example of Browser API
89+
90+
```javascript
91+
document.getElementById("myButton").addEventListener("click", () => {
92+
alert("Button clicked!");
93+
});
94+
```
95+
96+
### Example of Node.js API
97+
98+
```javascript
99+
const fs = require('fs');
100+
101+
fs.readFile('example.txt', 'utf8', (err, data) => {
102+
if (err) {
103+
console.error(err);
104+
return;
105+
}
106+
console.log(data);
107+
});
108+
```
109+
110+
### Conclusion
111+
112+
Understanding the runtime environment in JavaScript is crucial for writing efficient and effective code. By knowing how the call stack, memory heap, event loop, and provided APIs work, you can better manage your code's execution and performance.

0 commit comments

Comments
 (0)