# Javascript

### <mark style="color:red;">What are the features of JavaScript?</mark> What are the advantages of JavaScript over other web technologies?

1. **Dynamic Typing**: JavaScript allows variables to change their type at runtime, offering flexibility but requiring careful management to avoid runtime errors.
2. **Interpreter-Based**: It runs in the browser, interpreting code line by line, reducing development complexity without sacrificing performance.
3. **Validation of User’s Input**: JavaScript can validate user input before submission, enhancing security and user experience.
4. **In-built Functions**: Offers a wide range of built-in functions for common tasks, simplifying development.
5. **Case Sensitive**: Differentiates between uppercase and lowercase letters, affecting variable names and function calls.
6. **Lightweight and Delicate**: Efficiently handles operations without needing to declare variables, focusing on objects for operations.
7. **Async Processing**: Enables asynchronous operations through callbacks and promises, improving performance for IO-bound tasks.\\
8. **Saves Time and Bandwidth**: Executes on the client side, reducing load times and bandwidth consumption.
9. **Easily Sends HTTP Requests**: Utilizes XMLHttpRequest for asynchronous communication with servers without page reloads.
10. **Browser Compatibility**: Works across all modern browsers, ensuring consistent behavior and user experience
11. **Community Support**: Backed by global companies like Google (Angular) and Facebook (React.js), fostering a rich ecosystem of libraries and frameworks.
12. **Open Source**: Benefits from a wealth of open-source projects and extensive documentation, aiding rapid development and problem-solving.&#x20;
13. **Backend Usage**: Through Node.js, enables full-stack JavaScript development, streamlining development processes.
14. **Performance**: Fast execution due to client-side processing and just-in-time compilation by browsers.
15. **Reduced Server Load**: Being client-side, minimizes server demands, potentially eliminating the need for a server for simple applications.
16. **Rich Interfaces**: Enhances user experience with interactive features like drag-and-drop and sliders.
17. **Extended Functionality**: Allows extending web page functionalities with third-party add-ons.
18. **Versatility**: Capable of full-stack development with Node.js, enabling the creation of comprehensive JavaScript applications.
19. **More Features:**&#x20;
    * Lightweight
    * Cross-platform compatible
    * Object-oriented

### <mark style="color:red;">Explain Hoisting in JavaScript?</mark>

> *Hoisting is JavaScript's automatic behavior of moving all variable and function declarations to the top of their scope during the compilation phase, making them accessible throughout that scope before any code execution takes place*

**Why Hosting?**

> Understanding hoisting is essential for avoiding unexpected behavior in JavaScript programs. It **encourages developers to declare variables and functions at the beginning of their scope** to prevent confusion and potential bugs.

* **Scope**: This movement applies to both global and local scopes, meaning that regardless of where a variable or function is declared within a scope, it **becomes available at the top of that scope**.
* **Declaration vs. Initialization**: It's crucial to distinguish between hoisting declarations and initializations. While **declarations are hoisted, initializations are not.** This means that if a variable is declared and initialized after it's used, accessing it before its declaration will result in `undefined` for variables declared with `var`. For `let` and `const`, attempting to access them before declaration will throw an error because they are block-scoped and not initialized until their declaration.

> Consider the following example:

```javascript
console.log(x); // Output: undefined
var x = 5;
console.log(x); // Output: 5
```

Here’s what actually happens due to hoisting:

1. The variable declaration (`var x`) is hoisted to the top of its scope.
2. The variable assignment (`x = 5`) stays in place.

> So, the code is interpreted as:

```javascript
var x;
console.log(x); // Output: undefined
x = 5;
console.log(x); // Output: 5
```

> In contrast, `let` and `const` variables are hoisted but not initialized, leading to a "temporal dead zone" until the line where they are defined:

```javascript
console.log(y); 
// ReferenceError: Cannot access 'y' before initialization
let y = 10;
console.log(y); // Output: 10
```

* **Behavior with `var`**: When using `var`, the declaration is hoisted, but the initialization is not. This means that if you try to use a variable declared with `var` before it's initialized, it will return `undefined`.
* **Behavior with `let` and `const`**: Unlike `var`, `let` and `const` are block-scoped, and their declarations are hoisted to the top of their block. However, they are not initialized until their declaration statement is executed. Attempting to access them before their declaration will result in a Reference Error.
* **Function Declarations**: Both named and anonymous function declarations are hoisted, allowing them to be called before their declaration in the code. **However, function expressions (including those involving arrow functions) are not hoisted unless they are declared as named functions.**
* **Strict Mode**: In strict mode, undeclared variables are treated as `undefined` instead of being automatically declared as global variables, further emphasizing the importance of proper declaration practices.

<figure><img src="/files/vqAWkIJSIfp80O8ok9fI" alt=""><figcaption></figcaption></figure>

### <mark style="color:red;">What are the scopes of a variable in JavaScript?</mark>

In JavaScript, the scope of a variable determines its visibility and accessibility within different parts of the code. There are three primary scopes for variables:

* **Global Scope**: Variables declared outside any function have a global scope. They can be accessed from anywhere in the JavaScript program. Examples include variables declared with `var`, `let`, or `const` outside of any function or block.
* **Function Scope**: Each function in JavaScript creates a new scope. Variables declared within a function using `var`, `let`, or `const` are local to that function and are not accessible from outside the function. This means they can only be accessed within the function they were declared in.
* **Block Scope**: Introduced with ES6, `let` and `const` declarations have block scope. This means they are only accessible within the block they are declared in, including blocks within loops and conditionals. Variables declared with `var` do not have block scope; they are function-scoped or globally scoped depending on where they are declared.

```javascript
// Global scope
var globalVar = "I'm global!";
console.log(globalVar); // Accessible from anywhere

function exampleFunction() {
  // Function scope
  var localVar = "I'm local!";
  console.log(localVar); // Accessible within the function
  
  if (true) {
    // Block scope
    let blockScopedVar = "I'm block scoped!";
    console.log(blockScopedVar); // Accessible within the if block
    console.log(localVar); // Accessible within the if block cause function scope
  }
  console.log(blockScopedVar); // Error: blockScopedVar is not defined
  
}

exampleFunction(); // Call the function to see the output
console.log(globalVar); // Still accessible outside the function
console.log(localVar); // Error: localVar is not defined
console.log(blockScopedVar); // Error: blockScopedVar is not defined
```

### <mark style="color:red;">Difference between var and let keyword in JavaScript.</mark>

The `var` and `let` keywords in JavaScript are used to declare variables, but they differ significantly in terms of scope, hoisting behavior, and redeclaration rules:

* **Usage in Loops**:
  * `var`: When used in a loop, the variable retains its value after the loop completes, which can lead to unexpected behavior if not managed carefully.
  * `let`: When used in a loop, the variable is confined to the loop's block, and its value resets with each iteration, aligning with typical expectations for loop counters.

| var                                                                                       | let                                                                                          |
| ----------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| <p>Syntax -:</p><p><strong>var name = value.</strong></p>                                 | <p>Syntax -:</p><p><strong>let name = value.</strong></p>                                    |
| The variables that are defined with **var** statement have function scope.                | The variables that are defined with **let** statement have block scope.                      |
| We can declare a variable again even if it has been defined previously in the same scope. | We cannot declare a variable more than once if we defined that previously in the same scope. |
| Hoisting is allowed with **var**.                                                         | **let** is hoisted but inaccessible due to temporal dead zone                                |
| <p>Example -:</p><p><strong>var websitename = “geeksforgeeks”;</strong></p>               | <p>Example -:</p><p> <strong>let x = 69;</strong></p>                                        |
| var is an ECMAScript1 feature.                                                            | let is a feature of ES6.                                                                     |

In summary, `let` offers more precise control over variable scope and lifecycle, making it the preferred choice for modern JavaScript development. Its block scoping and strict handling of hoisting and redeclaration help prevent common pitfalls associated with `var`.

### <mark style="color:red;">Explain Implicit Type Coercion in JavaScript?</mark>

When the value of one data type is automatically converted into another data type, it is called Implicit type coercion in JavaScript.

```javascript
var a = 4;
var b = "2";

console.log(a+b); // converted to string = 42
console.log(a-b); // converted to number = 2
```

### <mark style="color:red;">Difference between “== “ and “ === “ operators ?</mark>

Both are comparison operators. The difference between both the operators is that “==” is used to compare values whereas, “ === “ is used to compare both values and types.

```javascript
let a = 0;
let b = false;
console.log((a == b));  // true
console.log((a === b)); // false
```

### <mark style="color:red;">What is the difference between Session storage and Local storage?</mark>

| Session storage                                                                      | Local storage                                                                                                                      |
| ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- |
| The data stored in session storage gets expired or deleted when a page session ends. | Websites store some data in local machine to reduce loading time; this data does not get deleted at the end of a browsing session. |

### <mark style="color:red;">What is the difference between Undefined and Null in JavaScript?</mark>

| Undefined means a variable has been declared but a value has not yet been assigned to that variable. | Null is an assignment value that we can assign to any variable that is meant to contain no value. |
| ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |

### <mark style="color:red;">Output of Following Codes</mark>

```javascript
(function(){
  setTimeout(()=> console.log(1),2000);
  console.log(2);
  setTimeout(()=> console.log(3),0);
  console.log(4);
})();

Output:
2 
4
3
1
```

### <mark style="color:red;">What is a self-invoked function? How does a self-invoked function work?</mark>

A self-invoked function, also known as an Immediately Invoked Function Expression (IIFE), is a function that is executed immediately after it is defined. This technique is commonly used in JavaScript to create a new scope and to avoid polluting the global namespace.

#### Structure of an Immediately Invoked Function Expression (IIFE)

An IIFE is typically structured as follows:

```javascript
(function() {
    console.log("This is a self-invoked function!");
})();
```

#### Why Use an IIFE?

1. **Avoid Global Variables**: Variables defined within an IIFE are not accessible outside its scope, which helps in preventing global namespace pollution.

   ```javascript
   code(function() {
       var secret = "I'm a secret!";
       console.log(secret); // This will log "I'm a secret!"
   })();

   console.log(secret); // This will throw a ReferenceError: secret is not defined
   ```
2. **Module Pattern**: IIFEs are often used in the module pattern to create private and public members.

   ```javascript
   var counterModule = (function() {
       var count = 0; // private variable
       
       return {
           increment: function() {
               count++;
               console.log(count);
           },
           reset: function() {
               count = 0;
               console.log(count);
           }
       };
   })();

   counterModule.increment(); // logs 1
   counterModule.increment(); // logs 2
   counterModule.reset(); // logs 0
   ```

   In this example, `count` is a private variable that can only be accessed and modified by the methods `increment` and `reset`.
3. **Immediate Initialization**: IIFEs can be used to initialize variables or set up configurations right away.

   ```javascript
   var appConfig = (function() {
       var config = {
           apiKey: '1234567890',
           apiUrl: 'https://api.example.com'
       };
       return config;
   })();

   console.log(appConfig.apiKey); /
   ```

### <mark style="color:red;">What happens if you initialize a variable in a block but do not declare it anywhere in the code?</mark>

If you initialize a variable in a block without declaring it anywhere in the code (i.e., without using `var`, `let`, or `const`), it will be treated as an implicit global variable in JavaScript. This happens because the JavaScript interpreter will automatically create a global variable with the given name.

Here is an example to illustrate this behavior:

```javascript
function example() {
    // No declaration with var, let, or const
    implicitGlobal = "I'm an implicit global variable!";
}

example();

console.log(implicitGlobal); // This will log: "I'm an implicit global variable!"
```

#### Why This Happens

* **Global Scope**: If a variable is assigned a value without being declared using `var`, `let`, or `const`, it will be added to the global object (`window` in browsers, `global` in Node.js). This makes it accessible from anywhere in the code.

### <mark style="color:red;">Let's assume a function receives 3 parameters but you call it using 2 parameters. a. What will happen? b. What will be the value of the 3rd parameter?</mark>

#### a. What will happen?

The function will execute without any error. JavaScript does not enforce a strict number of parameters, so it allows you to call a function with fewer or more arguments than it is defined to take.

#### b. What will be the value of the 3rd parameter?

The third parameter will be `undefined`. When a function is called with fewer arguments than the number of parameters defined, the parameters for which no corresponding arguments are provided will be set to `undefined`.

#### Example

Here is an example to illustrate this behavior:

```javascript
function exampleFunction(a, b, c) {
    console.log(a); // logs the value of the first argument
    console.log(b); // logs the value of the second argument
    console.log(c); // logs the value of the third argument, which will be undefined
}

exampleFunction(1, 2); // Only two arguments are provided
```

Output:

```javascript
1
2
undefined
```

In this example:

* `a` is assigned the value `1`.
* `b` is assigned the value `2`.
* `c` is not provided, so it is assigned `undefined`.

#### Handling Undefined Parameters

If you want to provide default values for parameters that might be undefined, you can use default parameter syntax:

```javascript
function exampleFunction(a, b, c = 3) {
    console.log(a); // logs the value of the first argument
    console.log(b); // logs the value of the second argument
    console.log(c); // logs the value of the third argument, which will be 3 if not provided
}

exampleFunction(1, 2); // Only two arguments are provided
```

Output:

```
1
2
3
```

In this modified example, `c` will default to `3` if it is not provided.

### <mark style="color:red;">Differences between declaring variables using var, let and cons?</mark>

When declaring variables in JavaScript, you have three options: `var`, `let`, and `const`. Each has its own characteristics and scope rules. Here's a detailed explanation of the differences:

#### 1. `var`

* **Scope**: `var` is function-scoped, meaning it is accessible within the function it is declared in. If declared outside any function, it becomes globally scoped.
* **Hoisting**: Variables declared with `var` are hoisted to the top of their scope. This means the declaration is processed before any code is executed, but the initialization is not. As a result, you can reference a `var` variable before its declaration without getting a `ReferenceError`, although its value will be `undefined` until the line where it's initialized is executed.
* **Re-declaration**: You can re-declare a variable using `var` within the same scope without any errors.
* **Example**:

  ```javascript
  function example() {
      console.log(x); // undefined due to hoisting
      var x = 5;
      console.log(x); // 5
  }
  example();

  var y = 10;
  var y = 20; // No error
  console.log(y); // 20
  ```

#### 2. `let`

* **Scope**: `let` is block-scoped, meaning it is only accessible within the block (enclosed by `{}`) it is declared in. This includes for-loops, if statements, etc.
* **Hoisting**: Variables declared with `let` are hoisted to the top of their block, but they are not initialized. This means referencing a `let` variable before its declaration results in a `ReferenceError`.
* **Re-declaration**: You cannot re-declare a variable using `let` within the same scope.
* **Example**:

  ```javascript
  function example() {
      console.log(x); // ReferenceError: Cannot access 'x' before initialization
      let x = 5;
      console.log(x); // 5
  }
  example();

  let y = 10;
  let y = 20; // SyntaxError: Identifier 'y' has already been declared
  ```

#### 3. `const`

* **Scope**: `const` is also block-scoped, similar to `let`.
* **Hoisting**: Variables declared with `const` are hoisted to the top of their block but are not initialized. Like `let`, referencing a `const` variable before its declaration results in a `ReferenceError`.
* **Re-declaration and Assignment**: You cannot re-declare or reassign a variable declared with `const`. This makes `const` useful for defining constants that should not change.
* **Mutable Objects**: Note that while you cannot reassign a `const` variable, if it holds an object or array, the properties or elements of that object/array can be changed.
* **Example**:

  ```javascript
  function example() {
      console.log(x); // ReferenceError: Cannot access 'x' before initialization
      const x = 5;
      console.log(x); // 5
  }
  example();

  const y = 10;
  y = 20; // TypeError: Assignment to constant variable.

  const obj = { key: 'value' };
  obj.key = 'newValue'; // Allowed
  console.log(obj.key); // 'newValue'
  ```

#### Summary

* **Scope**: `var` is function-scoped; `let` and `const` are block-scoped.
* **Hoisting**: All are hoisted, but `let` and `const` are not initialized until their declaration is encountered.
* **Re-declaration**: `var` allows re-declaration; `let` and `const` do not.
* **Assignment**: `const` does not allow reassignment; `var` and `let` do.

### <mark style="color:red;">Is JavaScript a statically typed or a dynamically typed language?</mark>

JavaScript is a dynamically typed language. In a dynamically typed language, variable types are determined at runtime, allowing a variable to hold values of any type without explicit type declarations. This flexibility can make coding more convenient but may also lead to runtime errors if types are not handled appropriately.

JavaScript, being dynamically typed, allows variables to change types during execution and accommodates a wide range of data types without explicit type annotations

### <mark style="color:blue;">What is Callback Hell?</mark>

Callback hell (or "pyramid of doom") is a situation in which multiple nested callbacks make the code difficult to read and maintain. This often occurs when dealing with asynchronous operations, such as making multiple API calls or handling multiple events.

Here's an example of callback hell:&#x20;

<pre class="language-javascript"><code class="lang-javascript">getUser(function(user) {
<strong>    getProfile(user.id, function(profile) {
</strong>        getPosts(user.id, function(posts) {
            displayUserProfile(user, profile, posts, function() {
            });
        });    
    });
});
</code></pre>

More nested callbacks... In this example, we have nested callbacks for getting a user, fetching their profile, retrieving their posts, and finally displaying the user profile. As more asynchronous operations are added, the code becomes more difficult to read and maintain.

To address callback hell, developers often use techniques like Promises or async/await in modern JavaScript to make code more readable and manageable

***

### <mark style="color:blue;">Writing clear and bug-free JavaScript</mark>

#### Examples of Poor Practice:

```javascript
// Non-descriptive variable names
let x = 100;
let y = 200;

// Using reserved words and unclear naming
let function = "functionName"; // Syntax error: reserved word
let temp = "John"; // What is 'temp' referring to?

// Inconsistent naming conventions
function CalculateTotalPrice(Items) { // Inconsistent function naming
    let Total_price = 0; // Inconsistent variable naming
    Items.forEach(Item => {
        Total_price += Item.Price;
    });
    return Total_price;
}
```

#### Examples of Good Practice:

```javascript
// Descriptive variable names using camelCase
let userFirstName = "John";
let userLastName = "Doe";
const MAX_LOGIN_ATTEMPTS = 3;

// Avoiding reserved words and using meaningful names
let isLoggedIn = false;
let userRole = "admin";

// Consistent naming for functions and variables
function calculateTotalPrice(items) {
    let totalPrice = 0;
    items.forEach(item => {
        totalPrice += item.price;
    });
    return totalPrice;
}
```

### <mark style="color:red;">What is the difference between Function declaration and Function expression?</mark>

<table><thead><tr><th width="60"></th><th>Function Declaration</th><th>Function Expression</th></tr></thead><tbody><tr><td>1</td><td>Function declarations are hoisted to the top of their containing scope. This means you can call the function before its definition in the code.</td><td>Function expressions are not hoisted. This means you cannot call the function before it is defined in the code.</td></tr><tr><td>2</td><td>Uses the <code>function</code> keyword followed by a name and parameter list.</td><td>Often assigned to a variable, can be anonymous or named, and defined using the <code>function</code> keyword.</td></tr><tr><td>3</td><td>Typically used for defining main functions that need to be available throughout the code.</td><td>Often used for inline functions, such as callbacks or immediately invoked function expressions (IIFEs).</td></tr></tbody></table>

#### **Syntax:** Function Declaration

```javascript
console.log(add(2, 3)); // Output: 5

function add(a, b) {
    return a + b;
}
```

#### **Syntax:** Function Expression

```javascript
// This will cause an error because the function is not hoisted
console.log(multiply(2, 3));
// Uncaught ReferenceError: Cannot access 'multiply' before initialization

const multiply = function(a, b) {
    return a + b;
};

console.log(multiply(2, 3)); // Output: 5
```

### <mark style="color:red;">What is the distinction between client-side and server-side JavaScript?</mark>

<table><thead><tr><th width="68"></th><th width="373">Client - Side JavaScript</th><th>Server - Side JavaScript</th></tr></thead><tbody><tr><td>1</td><td>Client-side JavaScript runs in the user's web browser, interacting with the web page's content and the browser itself.</td><td>Server-side JavaScript runs on the web server, handling backend logic, database interactions, and serving web pages to clients</td></tr><tr><td>2</td><td>Runs in the browser (e.g., Chrome, Firefox, Safari).</td><td>Runs on the server (e.g., Node.js).</td></tr><tr><td>3</td><td><p></p><p>Popular libraries and frameworks include jQuery, React, Angular, and Vue.js.</p></td><td>Popular frameworks include Express.js, Koa.js, and Hapi.js.</td></tr><tr><td>4</td><td><p><strong>Common Uses:</strong></p><ul><li>Manipulating the Document Object Model (DOM) to update the content, structure, and style of web pages dynamically.</li><li>Handling user events such as clicks, form submissions, and mouse movements.</li><li>Validating user input before it is sent to the server.</li><li>Making asynchronous requests to the server using AJAX (Asynchronous JavaScript and XML) or Fetch API to update parts of the web page without reloading.</li></ul></td><td><p><strong>Common Uses:</strong></p><ul><li>Handling HTTP requests and responses.</li><li>Interacting with databases, file systems, and other server resources.</li><li>Implementing business logic, authentication, and authorization.</li><li>Serving dynamic content and APIs to client-side applications.</li></ul></td></tr></tbody></table>

**Example:** Client-Side JavaScript

```html
// Client-Side JavaScript
<!DOCTYPE html>
<html>
<head>
    <title>Client-Side JavaScript Example</title>
    <script>
        function showAlert() {
            alert("Button clicked!");
        }
    </script>
</head>
<body>
    <button onclick="showAlert()">Click Me</button>
</body>
</html>
```

**Example:** Server-Side JavaScript

```javascript
// Server-Side JavaScript using Node.js and Express.js
const express = require('express');
const app = express();

app.get('/', (req, res) => {
    res.send('Hello from the server!');
});

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});
```

### <mark style="color:red;">Explain the key features introduced in JavaScript ES6</mark>

ECMAScript 6 (ES6), also known as ECMAScript 2015, introduced a number of key features that significantly enhanced JavaScript's functionality and usability. Here are the major features:

#### 1. **let and const**

* **let:** Declares block-scoped variables.
* **const:** Declares block-scoped constants that cannot be reassigned.

```javascript
let variable = 'value';
const constant = 'constant value';
```

#### 2. **Arrow Functions**

* Provide a shorter syntax for writing function expressions and lexically bind this value.

```javascript
const add = (a, b) => a + b;
```

#### 3. **Template Literals**

* Allow embedded expressions and multi-line strings using backticks (\`) instead of single or double quotes.

```javascript
const name = 'World';
const greeting = `Hello, ${name}!`;
```

#### 4. **Default Parameters**

* Allow function parameters to have default values.

```javascript
function greet(name = 'Guest') {
    return `Hello, ${name}!`;
}
```

#### 5. **Destructuring Assignment**

* Allows unpacking values from arrays or properties from objects into distinct variables.

```javascript
// Array Destructuring
const [a, b] = [1, 2];

// Object Destructuring
const {name, age} = {name: 'Alice', age: 25};
```

#### 6. **Enhanced Object Literals**

* Simplify object property definitions.

```javascript
const name = 'Alice';
const age = 25;
const person = {
    name,
    age,
    greet() {
        console.log('Hello!');
    }
};
```

#### 7. **Modules**

* Allow code to be split into modules that can be imported and exported.

```javascript
// module.js
export const name = 'Alice';
export function greet() {
    console.log('Hello!');
}

// main.js
import {name, greet} from './module.js';
```

#### 8 **Promises**

* Provide a way to handle asynchronous operations.

```javascript
const fetchData = new Promise((resolve, reject) => {
    // Simulate an async operation
    setTimeout(() => resolve('Data fetched'), 1000);
});

fetchData.then(data => console.log(data));
```

#### 9. **Rest and Spread Operators**

* Rest operator (`...`) allows for variable numbers of arguments.
* Spread operator (`...`) allows an iterable to be expanded in places where zero or more arguments are expected.

```javascript
// Rest Parameter
function sum(...numbers) {
    return numbers.reduce((total, num) => total + num, 0);
}

// Spread Operator
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5, 6];
```

#### 10. **Iterators and for...of Loop**

* Provide a way to iterate over iterable objects (like arrays, strings, etc.).

```javascript
const array = [1, 2, 3, 4];
for (const value of array) {
    console.log(value);
}
```

### <mark style="color:red;">What do you understand about cookies?</mark>

Cookies are small pieces of data stored on the user's computer by the web browser while browsing a website. They are used for various purposes, including session management, personalization, and tracking user behavior. Here's a detailed understanding of cookies:

#### Key Characteristics of Cookies

1. **Storage:**
   * Cookies are stored in the user's web browser and can persist between sessions.
2. **Expiration:**
   * Cookies can have an expiration date set by the server. If no expiration date is set, t**he cookie is a session cookie and will be deleted when the browser is closed.**
   * Persistent cookies remain until the specified expiration date or until manually deleted by the user.

#### Types of Cookies

1. **Session Cookies:**
   * Temporary cookies that are deleted when the browser is closed.
   * Used for session management, like keeping users logged in as they navigate through a site.
2. **Persistent Cookies:**
   * Remain on the user's device until they expire or are deleted.
   * Used for storing preferences, authentication tokens, and other information that should persist between sessions.
3. **Third-Party Cookies:**
   * Set by domains other than the one the user is currently visiting.
   * Commonly used for tracking and advertising purposes.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sumontas-organization.gitbook.io/internship-preparation-2024/javascript-+-react/javascript.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
