> For the complete documentation index, see [llms.txt](https://riteshs4hu.gitbook.io/infosec-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://riteshs4hu.gitbook.io/infosec-notes/language/javascript-js/basic-of-js.md).

# Basic of JS

JavaScript is a **single-threaded** language, meaning it can execute **one task at a time** using a **single call stack**. However, JavaScript can also handle asynchronous operations like timers, API calls, and event listeners without blocking execution. This is possible due to the **Event Loop**.

#### **Components of the Event Loop**

The Event Loop works with the following components:

1. **Call Stack** (Execution Stack)
2. **Web APIs** (Browser APIs)
3. **Callback Queue** (Task Queue / Message Queue)
4. **Microtask Queue** (Promise Queue)
5. **Event Loop**

***

#### **1. Call Stack**

The **Call Stack** is a **LIFO (Last In, First Out)** data structure that manages the execution of JavaScript code. Whenever a function is called, it is pushed onto the stack, and when execution completes, it is popped off the stack.

Example:

```javascript
function first() {
    console.log("First");
}
function second() {
    console.log("Second");
}
first();
second();
```

**Execution Flow (Call Stack)**

```
Call Stack:
-> first()
-> console.log("First")  // Prints "First"
-> second()
-> console.log("Second") // Prints "Second"
```

Since JavaScript is synchronous by default, it executes each function in order before moving to the next.

***

#### **2. Web APIs (Browser APIs)**

JavaScript on the browser does not directly handle tasks like timers, HTTP requests, or DOM manipulation. Instead, it delegates these to **Web APIs** provided by the browser.

Examples of Web APIs:

* `setTimeout()`
* `fetch()`
* DOM Manipulation
* WebSockets

Example:

```javascript
console.log("Start");

setTimeout(() => {
    console.log("Timeout Callback");
}, 2000);

console.log("End");
```

**Execution Flow**

1. `"Start"` is logged.
2. `setTimeout()` is encountered and handed over to the **Web API (Timer)**.
3. `"End"` is logged.
4. After 2 seconds, the **callback function** is placed in the **Callback Queue**.
5. The **Event Loop** pushes the callback onto the **Call Stack** when it's empty.
6. `"Timeout Callback"` is logged.

***

#### **3. Callback Queue (Task Queue)**

The **Callback Queue** holds **asynchronous tasks** that are ready to execute after completing in Web APIs.

Tasks added to the Callback Queue:

* `setTimeout()`
* `setInterval()`
* DOM Events like `click`, `keydown`
* `fetch()` (when using `then()` callback)

When the Call Stack is **empty**, the **Event Loop** picks tasks from the **Callback Queue** and pushes them into the Call Stack.

***

#### **4. Microtask Queue (Priority Queue)**

The **Microtask Queue** is similar to the Callback Queue, but it has **higher priority**. It mainly contains:

* **Promises (`.then()` and `.catch()`)**
* **Mutation Observers**

Example:

```javascript
console.log("Start");

setTimeout(() => console.log("setTimeout"), 0);

Promise.resolve().then(() => console.log("Promise"));

console.log("End");
```

**Execution Flow**

1. `"Start"` is logged.
2. `setTimeout()` is handled by the **Web API**.
3. A **Promise** is resolved and added to the **Microtask Queue**.
4. `"End"` is logged.
5. **Microtask Queue (Promise) executes first → `"Promise"` is logged**.
6. **Callback Queue (setTimeout) executes next → `"setTimeout"` is logged**.

> **Microtasks always execute before Macrotasks (setTimeout, setInterval).**

***

#### **5. The Event Loop**

The **Event Loop** is the mechanism that continuously checks:

1. **Is the Call Stack empty?**
2. **Are there any tasks in the Microtask Queue? (Execute first)**
3. **Are there tasks in the Callback Queue? (Execute after Microtasks)**

It ensures JavaScript runs asynchronously without blocking execution.

***

### **Example with Event Loop**

```javascript
console.log("Start");

setTimeout(() => console.log("setTimeout"), 0);

Promise.resolve().then(() => console.log("Promise 1"));
Promise.resolve().then(() => console.log("Promise 2"));

console.log("End");
```

#### **Execution Order**

1. `"Start"` → **Call Stack**
2. `setTimeout()` → **Web API (Timer)**
3. **Promises** go to **Microtask Queue**
4. `"End"` → **Call Stack**
5. **Microtask Queue executes first** → `"Promise 1"`, `"Promise 2"`
6. **Callback Queue executes** → `"setTimeout"`

**Final Output**

```
Start
End
Promise 1
Promise 2
setTimeout
```

***

## Event Loop

JavaScript is a **synchronous, single-threaded** language, meaning it has only one **call stack** to execute code. However, it can handle asynchronous operations using the **Event Loop**.

#### Synchronous vs. Asynchronous Operations

* **Synchronous**: Code is executed line by line, blocking further execution until the current operation is completed.
* **Asynchronous**: Code execution is non-blocking, meaning the program can continue running while waiting for certain operations (like fetching data or waiting for a timer) to complete.

### Call Stack

The **Call Stack** is a mechanism inside the JavaScript engine that manages function execution. It follows the **LIFO (Last In, First Out)** principle and does not wait for any operation—it executes code sequentially.

#### LIFO (Last In, First Out)

LIFO is a method where the most recently added function is executed first and removed from the stack before the previous one. This ensures that the last called function is resolved before earlier calls.

#### What if a Program Requires a Delay?

JavaScript code running on the **Call Stack** may need access to timers, page rendering, Bluetooth, or other browser functionalities. This is where **Web APIs** come into play.

### Browser Overview

Inside the browser, apart from the **JavaScript engine**, there are various built-in APIs such as:

* **Timers** (setTimeout, setInterval)
* **URL handling**
* **DOM manipulation**
* **Display rendering**
* **Bluetooth access**
* **Webcam access**

The browser provides these **Web APIs** to JavaScript through the **Global Object (window)**.

#### Web APIs Examples:

* `setTimeout()`
* `DOM APIs`
* `fetch()`
* `localStorage`
* `console`
* `location`

#### Document Object Model (DOM)

The **DOM (Document Object Model)** represents the HTML structure of a webpage in an object-oriented format. JavaScript can interact with the DOM to modify elements dynamically.

#### Example:

```javascript
console.log("Run");

setTimeout(function cb(){
    console.log("Callback");
}, 5000);

console.log("Exit");
```

**Execution Flow:**

1. **First**, `console.log("Run")` is added to the Call Stack and executed.
2. **Then**, `setTimeout()` is called, which is handled by the **Web API** and the callback function is scheduled.
3. **Next**, `console.log("Exit")` is executed immediately.
4. **After 5000ms**, the callback function is pushed onto the Call Stack and executed.

### JavaScript Engine

The JavaScript engine processes and executes JavaScript code through the following steps:

1. **Parsing** → Converts code into an **Abstract Syntax Tree (AST)**.
2. **Compilation** → Uses **Just-In-Time (JIT) Compilation**.
3. **Execution** → Runs the optimized code.

#### Components of the JavaScript Engine:

* **Parsing**
* **Compilation**
  * Optimization techniques: **Inlining, Copy Elision, Inline Caching**
* **Execution**
* **Interpreter & Compiler**
* **Memory Heap** (Garbage Collector using **Mark & Sweep Algorithm**)
* **Call Stack**

#### Interpreter & Compiler

* **Interpreter**: Reads and executes code **line by line**, making execution fast but potentially inefficient.
* **Compiler**: Translates the entire code before execution, optimizing it for better performance.

### Just-In-Time (JIT) Compilation

The JavaScript engine uses **both an Interpreter and a Compiler**:

#### Interpreter:

1. Reads and executes code **line by line**.
2. Fast execution but not optimized.

#### Compiler:

1. Compiles code **before execution**, optimizing it.
2. More efficient than interpretation alone.

Some engines use **Ahead-of-Time (AOT) Compilation**, where code that is going to be executed later is precompiled and optimized into **bytecode**.

### Ahead-of-Time (AOT) Compilation

Unlike JIT compilation, **AOT compilation** converts the code into machine code **before** execution, reducing runtime overhead.

### V8 JavaScript Engine

The **V8 Engine** (used in Chrome and Node.js) follows this architecture:

1. **JavaScript Source Code** →
2. **Parser** → Converts code into an **AST**
3. **Interpreter (Ignition)** → Generates **Bytecode**
4. **Compiler (TurboFan)** → Converts **Bytecode** into optimized **Machine Code**

#### Garbage Collection in V8

V8 uses **Oilpan** for memory management. It employs **Mark & Sweep Garbage Collection**, which automatically frees up memory by removing unused objects.
