{"id":23073695,"url":"https://github.com/akashdip2001/javascript","last_synced_at":"2026-04-28T08:31:47.973Z","repository":{"id":265093051,"uuid":"869774914","full_name":"akashdip2001/JavaScript","owner":"akashdip2001","description":"JavaScript notes + Projects","archived":false,"fork":false,"pushed_at":"2024-12-01T12:57:16.000Z","size":167,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-09T00:45:07.303Z","etag":null,"topics":["backend","javascript","node-js","nodejs","project","study-notes"],"latest_commit_sha":null,"homepage":"https://github.com/akashdip2001/JavaScript/blob/main/Projects%20link.md","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/akashdip2001.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-10-08T21:36:45.000Z","updated_at":"2024-12-21T13:48:18.000Z","dependencies_parsed_at":"2025-02-09T00:45:00.191Z","dependency_job_id":"97aab9aa-b4cf-45e1-adf8-f70cd711d5cc","html_url":"https://github.com/akashdip2001/JavaScript","commit_stats":null,"previous_names":["akashdip2001/javascript"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akashdip2001%2FJavaScript","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akashdip2001%2FJavaScript/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akashdip2001%2FJavaScript/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akashdip2001%2FJavaScript/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/akashdip2001","download_url":"https://codeload.github.com/akashdip2001/JavaScript/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246991977,"owners_count":20865748,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["backend","javascript","node-js","nodejs","project","study-notes"],"created_at":"2024-12-16T08:18:45.517Z","updated_at":"2026-04-28T08:31:42.932Z","avatar_url":"https://github.com/akashdip2001.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# JavaScript Study Guide\n\nWelcome to your comprehensive JavaScript study guide! This document is meticulously structured to help you prepare for your upcoming job exam and excel in your JavaScript endeavors. It covers fundamental to advanced JavaScript concepts, complete with explanations, code examples, and best practices. Additionally, it includes essential topics like setting up your development environment with **Visual Studio Code (VS Code)** and **Node.js**, important points for job interviews, and references to the best documentation resources.\n\n---\n\n## Table of Contents\n\n1. [Introduction to JavaScript](#introduction-to-javascript)\n2. [Setting Up Your Development Environment](#setting-up-your-development-environment)\n    - [Installing Visual Studio Code](#installing-visual-studio-code)\n    - [Installing Node.js and npm](#installing-nodejs-and-npm)\n    - [Configuring VS Code for JavaScript Development](#configuring-vs-code-for-javascript-development)\n3. [Executing JavaScript](#executing-javascript)\n    - [Inline in HTML](#inline-in-html)\n    - [Internal Script](#internal-script)\n    - [External Script](#external-script)\n    - [Running JavaScript with Node.js](#running-javascript-with-nodejs)\n4. [Basic JavaScript Concepts](#basic-javascript-concepts)\n    - [Writing to Document](#writing-to-document)\n    - [Variables](#variables)\n    - [Data Types](#data-types)\n    - [Operators](#operators)\n    - [Mathematical Operations](#mathematical-operations)\n    - [Math Functions](#math-functions)\n    - [String Functions](#string-functions)\n    - [Logical Operators](#logical-operators)\n5. [Control Structures](#control-structures)\n    - [If-Else Conditions](#if-else-conditions)\n    - [Switch Statements](#switch-statements)\n6. [Loops](#loops)\n    - [While Loop](#while-loop)\n    - [Do-While Loop](#do-while-loop)\n    - [For Loop](#for-loop)\n    - [For...of and For...in Loops](#forof-and-forin-loops)\n7. [Arrays](#arrays)\n8. [Functions](#functions)\n    - [Function Declaration](#function-declaration)\n    - [Function Expressions](#function-expressions)\n    - [Arrow Functions](#arrow-functions)\n9. [DOM Manipulation](#dom-manipulation)\n10. [Error Handling](#error-handling)\n11. [Advanced JavaScript Concepts](#advanced-javascript-concepts)\n    - [Closures](#closures)\n    - [Hoisting](#hoisting)\n    - [Prototype and Inheritance](#prototype-and-inheritance)\n    - [Event Loop and Asynchronous JavaScript](#event-loop-and-asynchronous-javascript)\n12. [Node.js](#nodejs)\n    - [Introduction to Node.js](#introduction-to-nodejs)\n    - [Setting Up a Node.js Project](#setting-up-a-nodejs-project)\n    - [Using npm (Node Package Manager)](#using-npm-node-package-manager)\n    - [Creating a Simple Server with Node.js](#creating-a-simple-server-with-nodejs)\n13. [Important Interview Topics](#important-interview-topics)\n14. [Best Documentation Resources](#best-documentation-resources)\n15. [Conclusion](#conclusion)\n\n---\n\n## Introduction to JavaScript\n\n**JavaScript** is a versatile, high-level programming language primarily used for creating interactive and dynamic content on web pages. It is a client-side scripting language that runs in the user's browser, allowing developers to implement complex features on web pages without the need for page reloads.\n\n**Key Features:**\n- **Dynamic Typing:** Variables can hold different data types at different times.\n- **Prototype-Based:** JavaScript uses prototypes for inheritance.\n- **First-Class Functions:** Functions can be treated as variables.\n- **Event-Driven:** JavaScript can respond to user interactions.\n\n**Use Cases:**\n- **Web Development:** Enhancing user interfaces and experiences.\n- **Server-Side Development:** Building scalable network applications using Node.js.\n- **Mobile App Development:** Creating cross-platform mobile applications with frameworks like React Native.\n- **Game Development:** Developing browser-based games.\n\n---\n\n## Setting Up Your Development Environment\n\nA robust development environment is crucial for efficient coding and debugging. This section guides you through installing and configuring **Visual Studio Code (VS Code)** and **Node.js**, two essential tools for modern JavaScript development.\n\n### Installing Visual Studio Code\n\n**Visual Studio Code (VS Code)** is a powerful, open-source code editor developed by Microsoft. It offers extensive features like syntax highlighting, intelligent code completion, and built-in Git support.\n\n**Installation Steps:**\n\n1. **Download VS Code:**\n   - Visit the [official VS Code website](https://code.visualstudio.com/).\n   - Choose the appropriate installer for your operating system (Windows, macOS, or Linux).\n\n2. **Install VS Code:**\n   - Run the downloaded installer and follow the on-screen instructions.\n   - **Windows Users:** During installation, you can choose to add VS Code to your system PATH for easier command-line usage.\n\n3. **Launch VS Code:**\n   - After installation, open VS Code.\n   - Familiarize yourself with the interface, including the sidebar, editor pane, and integrated terminal.\n\n### Installing Node.js and npm\n\n**Node.js** is a JavaScript runtime built on Chrome's V8 engine, enabling JavaScript to run outside the browser. It is essential for server-side development and managing project dependencies.\n\n**npm (Node Package Manager):** Comes bundled with Node.js, allowing you to install, manage, and share packages (libraries) for your projects.\n\n**Installation Steps:**\n\n1. **Download Node.js:**\n   - Visit the [official Node.js website](https://nodejs.org/).\n   - Download the LTS (Long-Term Support) version for stability.\n\n2. **Install Node.js:**\n   - Run the downloaded installer and follow the installation prompts.\n   - **Windows Users:** Ensure the option to add Node.js to the system PATH is selected.\n\n3. **Verify Installation:**\n   - Open your terminal or command prompt.\n   - Run the following commands to verify:\n     ```bash\n     node -v\n     npm -v\n     ```\n   - You should see the installed versions of Node.js and npm.\n\n### Configuring VS Code for JavaScript Development\n\nEnhance your VS Code experience by installing extensions that boost productivity and provide better JavaScript support.\n\n**Recommended Extensions:**\n\n1. **ESLint:** Integrates ESLint into VS Code for real-time linting.\n   - **Installation:**\n     - Go to the Extensions view (`Ctrl+Shift+X` or `Cmd+Shift+X`).\n     - Search for \"ESLint\" and install the extension by Dirk Baeumer.\n\n2. **Prettier - Code Formatter:** Automatically formats your code for consistency.\n   - **Installation:**\n     - Search for \"Prettier\" in the Extensions view and install it.\n\n3. **Live Server:** Launches a local development server with live reload feature.\n   - **Installation:**\n     - Search for \"Live Server\" and install it.\n   - **Usage:**\n     - Right-click your `index.html` file and select \"Open with Live Server.\"\n\n4. **JavaScript (ES6) Code Snippets:** Provides JavaScript code snippets for faster coding.\n   - **Installation:**\n     - Search for \"JavaScript (ES6) code snippets\" and install it.\n\n5. **Debugger for Chrome:** Debug JavaScript code in the Google Chrome browser.\n   - **Installation:**\n     - Search for \"Debugger for Chrome\" and install it.\n\n**Configuration Tips:**\n\n- **Setting Prettier as Default Formatter:**\n  - Open settings (`Ctrl+,` or `Cmd+,`).\n  - Search for \"Default Formatter\" and select \"Prettier - Code formatter.\"\n  - Enable \"Format on Save\" to automatically format your code upon saving.\n\n- **ESLint Integration:**\n  - Initialize ESLint in your project by running:\n    ```bash\n    npm init -y\n    npm install eslint --save-dev\n    npx eslint --init\n    ```\n  - Follow the prompts to configure ESLint based on your project's needs.\n\n---\n\n## Executing JavaScript\n\nJavaScript can be executed in multiple environments and through various methods. Understanding these will help you choose the right approach for your projects.\n\n### Inline in HTML\n\nEmbedding JavaScript directly within HTML elements.\n\n**Example:**\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml\u003e\n\u003chead\u003e\n    \u003ctitle\u003eInline JavaScript\u003c/title\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n    \u003cbutton onclick=\"alert('Hello, World!')\"\u003eClick Me\u003c/button\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n**Explanation:**\n- The `onclick` attribute triggers a JavaScript `alert` when the button is clicked.\n\n### Internal Script\n\nPlacing JavaScript code within the `\u003cscript\u003e` tags inside the HTML file.\n\n**Example:**\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml\u003e\n\u003chead\u003e\n    \u003ctitle\u003eInternal JavaScript\u003c/title\u003e\n    \u003cscript type=\"text/javascript\"\u003e\n        // This is an internal script\n        function showMessage() {\n            alert(\"Hello from internal JavaScript!\");\n        }\n    \u003c/script\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n    \u003cbutton onclick=\"showMessage()\"\u003eClick Me\u003c/button\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n**Explanation:**\n- The JavaScript function `showMessage` is defined within the `\u003chead\u003e` section.\n- The button triggers the function upon clicking.\n\n### External Script\n\nLinking an external JavaScript file to your HTML document using the `src` attribute.\n\n**Example:**\n- **test.html**\n  ```html\n  \u003c!DOCTYPE html\u003e\n  \u003chtml\u003e\n  \u003chead\u003e\n      \u003ctitle\u003eExternal JavaScript\u003c/title\u003e\n      \u003cscript type=\"text/javascript\" src=\"test.js\"\u003e\u003c/script\u003e\n  \u003c/head\u003e\n  \u003cbody\u003e\n      \u003cp id=\"th\"\u003e\u003c/p\u003e\n      \u003cbutton onclick=\"changeText()\"\u003eChange Text\u003c/button\u003e\n  \u003c/body\u003e\n  \u003c/html\u003e\n  ```\n\n- **test.js**\n  ```javascript\n  // This is an external JavaScript file\n  function changeText() {\n      document.getElementById('th').innerHTML = \"This is a paragraph changed by external JS.\";\n  }\n  ```\n\n**Explanation:**\n- The `test.js` file contains JavaScript functions.\n- The HTML file links to `test.js` using the `src` attribute.\n- The button in the HTML triggers the `changeText` function to modify the paragraph's content.\n\n### Running JavaScript with Node.js\n\nNode.js allows you to execute JavaScript code outside the browser, making it ideal for server-side development.\n\n**Example:**\n\n- **hello.js**\n  ```javascript\n  // This is a Node.js script\n  console.log(\"Hello from Node.js!\");\n  ```\n\n- **Execution:**\n  ```bash\n  node hello.js\n  ```\n\n**Output:**\n```\nHello from Node.js!\n```\n\n**Explanation:**\n- The `console.log` statement outputs text to the terminal.\n- Running `node hello.js` executes the script and displays the message.\n\n**Creating a Simple Node.js Server:**\n\n- **server.js**\n  ```javascript\n  const http = require('http');\n\n  const hostname = '127.0.0.1';\n  const port = 3000;\n\n  const server = http.createServer((req, res) =\u003e {\n      res.statusCode = 200;\n      res.setHeader('Content-Type', 'text/plain');\n      res.end('Hello, World!\\n');\n  });\n\n  server.listen(port, hostname, () =\u003e {\n      console.log(`Server running at http://${hostname}:${port}/`);\n  });\n  ```\n\n- **Execution:**\n  ```bash\n  node server.js\n  ```\n\n**Accessing the Server:**\n- Open your browser and navigate to `http://127.0.0.1:3000/`.\n- You should see the message: **\"Hello, World!\"**\n\n**Explanation:**\n- The script creates a simple HTTP server that responds with \"Hello, World!\" to any request.\n- `http.createServer` sets up the server logic.\n- `server.listen` starts the server on the specified hostname and port.\n\n---\n\n## Basic JavaScript Concepts\n\nUnderstanding the fundamental concepts of JavaScript is essential for building robust applications. This section covers the basics, including variables, data types, operators, and functions.\n\n### Writing to Document\n\n**`document.write()`** and **`document.getElementById().innerHTML`** are two primary methods to manipulate HTML content using JavaScript.\n\n**Examples:**\n\n1. **Using `document.write()`:**\n    ```javascript\n    document.write(\"This is an external JS file.\u003cbr\u003e\");\n    ```\n\n    **Explanation:**\n    - Writes the specified text directly to the HTML document.\n    - `\u003cbr\u003e` adds a line break.\n\n2. **Using `document.getElementById().innerHTML`:**\n    ```javascript\n    document.getElementById('th').innerHTML = \"This is a paragraph changed by external JS.\";\n    ```\n\n    **Explanation:**\n    - Selects the HTML element with the ID `th`.\n    - Changes its content to the specified string.\n\n### Variables\n\nVariables store data values. In JavaScript, variables can be declared using `var`, `let`, or `const`.\n\n1. **`var`:** Function-scoped variable. Can be redeclared and updated.\n    ```javascript\n    var a1 = 45;\n    var a11 = 5;\n    ```\n\n2. **`let`:** Block-scoped variable. Can be updated but not redeclared within the same scope.\n    ```javascript\n    let a2 = \"This is me\";\n    ```\n\n3. **`const`:** Block-scoped constant. Cannot be updated or redeclared.\n    ```javascript\n    const PI = 3.14;\n    ```\n\n**Examples:**\n```javascript\nvar a1 = 45;\nvar a11 = 5;\nvar a2 = \"This is me\";\ndocument.write(a1 + a11 + \"\u003cbr\u003e\"); // Outputs: 50\ndocument.write(a1 + \", \" + a11 + \"\u003cbr\u003e\"); // Outputs: 45, 5\n```\n\n**Best Practices:**\n- Use `let` and `const` instead of `var` to leverage block scoping.\n- Prefer `const` for variables that shouldn't be reassigned.\n- Use meaningful variable names for better code readability.\n\n### Data Types\n\nJavaScript has several data types that classify the type of data stored in variables.\n\n#### Primitive Types\n\n1. **String:**\n    ```javascript\n    var str = \"Hello, World!\";\n    ```\n\n2. **Number:**\n    ```javascript\n    var num = 42;\n    ```\n\n3. **Boolean:**\n    ```javascript\n    var isActive = true;\n    ```\n\n4. **Undefined:**\n    ```javascript\n    var x;\n    console.log(x); // Outputs: undefined\n    ```\n\n5. **Null:**\n    ```javascript\n    var y = null;\n    console.log(y); // Outputs: null\n    ```\n\n#### Complex Types\n\n1. **Object:**\n    ```javascript\n    var person = {name: \"Alice\", age: 25};\n    ```\n\n2. **Array:**\n    ```javascript\n    var fruits = [\"Apple\", \"Banana\", \"Cherry\"];\n    ```\n\n3. **Function:**\n    ```javascript\n    function greet() {\n        console.log(\"Hello!\");\n    }\n    ```\n\n**Example:**\n```javascript\nvar str = \"Hello, World!\";\nvar num = 100;\nvar isActive = true;\nvar arr = [\"Apple\", \"Banana\", \"Cherry\"];\nvar obj = {name: \"Alice\", age: 25};\n```\n\n**Type Checking:**\n- **`typeof` Operator:**\n    ```javascript\n    console.log(typeof str); // Outputs: string\n    console.log(typeof num); // Outputs: number\n    console.log(typeof isActive); // Outputs: boolean\n    console.log(typeof arr); // Outputs: object\n    console.log(typeof obj); // Outputs: object\n    console.log(typeof greet); // Outputs: function\n    ```\n\n### Operators\n\nOperators perform operations on variables and values. JavaScript supports various types of operators, including arithmetic, assignment, comparison, and logical operators.\n\n#### Mathematical Operations\n\n1. **Addition (`+`):**\n    ```javascript\n    document.write(\"5 + 9 = \" + (5 + 9) + \"\u003cbr\u003e\"); // Outputs: 5 + 9 = 14\n    ```\n\n2. **Subtraction (`-`):**\n    ```javascript\n    document.write(\"5 - 9 = \" + (5 - 9) + \"\u003cbr\u003e\"); // Outputs: 5 - 9 = -4\n    ```\n\n3. **Multiplication (`*`):**\n    ```javascript\n    document.write(\"5 * 9 = \" + (5 * 9) + \"\u003cbr\u003e\"); // Outputs: 5 * 9 = 45\n    ```\n\n4. **Division (`/`):**\n    ```javascript\n    document.write(\"5 / 9 = \" + (5 / 9) + \"\u003cbr\u003e\"); // Outputs: 5 / 9 = 0.5555555555555556\n    ```\n\n5. **Modulus (`%`):**\n    ```javascript\n    document.write(\"5 % 9 = \" + (5 % 9) + \"\u003cbr\u003e\"); // Outputs: 5 % 9 = 5\n    ```\n\n#### Assignment Operators\n\n1. **Assignment (`=`):**\n    ```javascript\n    var a = 10;\n    ```\n\n2. **Addition Assignment (`+=`):**\n    ```javascript\n    a += 5; // a = a + 5\n    ```\n\n3. **Subtraction Assignment (`-=`):**\n    ```javascript\n    a -= 3; // a = a - 3\n    ```\n\n4. **Multiplication Assignment (`*=`):**\n    ```javascript\n    a *= 2; // a = a * 2\n    ```\n\n5. **Division Assignment (`/=`):**\n    ```javascript\n    a /= 4; // a = a / 4\n    ```\n\n#### Comparison Operators\n\nComparison operators are used to compare two values and return a Boolean (`true` or `false`).\n\n| Operator | Description                                  | Example        | Result                                  |\n|----------|----------------------------------------------|----------------|-----------------------------------------|\n| `==`     | Equal to                                     | `x == y`       | `true` if `x` equals `y`                |\n| `===`    | Strict equal to (checks type and value)      | `x === y`      | `true` if `x` equals `y` and same type  |\n| `!=`     | Not equal to                                 | `x != y`       | `true` if `x` does not equal `y`        |\n| `!==`    | Strict not equal to (checks type and value)  | `x !== y`      | `true` if `x` does not equal `y` or different type |\n| `\u003c`      | Less than                                    | `x \u003c y`        | `true` if `x` is less than `y`          |\n| `\u003e`      | Greater than                                 | `x \u003e y`        | `true` if `x` is greater than `y`       |\n| `\u003c=`     | Less than or equal to                        | `x \u003c= y`       | `true` if `x` is less than or equal to `y` |\n| `\u003e=`     | Greater than or equal to                     | `x \u003e= y`       | `true` if `x` is greater than or equal to `y` |\n\n**Examples:**\n```javascript\nconsole.log(\"The value of 1 == 4 is \" + (1 == 4)); // Outputs: The value of 1 == 4 is false\nconsole.log(\"The value of 1 != 4 is \" + (1 != 4)); // Outputs: The value of 1 != 4 is true\nconsole.log(\"The value of 1 \u003e= 4 is \" + (1 \u003e= 4)); // Outputs: The value of 1 \u003e= 4 is false\nconsole.log(\"The value of 1 \u003c= 4 is \" + (1 \u003c= 4)); // Outputs: The value of 1 \u003c= 4 is true\n```\n\n### Mathematical Operations\n\nPerforming calculations using arithmetic operators.\n\n**Example:**\n```javascript\nvar foodCost = prompt(\"What is the total amount?\");\nvar numberOfPeople = prompt(\"Number of people:\");\ndocument.write(\"The total cost of food was \" + foodCost + \"\u003cbr\u003e\");\ndocument.write(\"Each one of you has to pay \" + (foodCost / numberOfPeople).toFixed(2) + \"\u003cbr\u003e\");\n```\n\n**Explanation:**\n- Prompts the user to enter the total food cost and number of people.\n- Calculates the cost per person and displays it with two decimal places using `toFixed(2)`.\n\n### Math Functions\n\nJavaScript's `Math` object provides various mathematical functions and constants.\n\n**Common Math Functions:**\n\n1. **`Math.pow(x, y)`**: Raises `x` to the power of `y`.\n    ```javascript\n    document.write(\"2^9 = \" + Math.pow(2, 9) + \"\u003cbr\u003e\"); // Outputs: 2^9 = 512\n    ```\n\n2. **`Math.abs(x)`**: Returns the absolute value of `x`.\n    ```javascript\n    document.write(\"abs(-34) = \" + Math.abs(-34) + \"\u003cbr\u003e\"); // Outputs: abs(-34) = 34\n    ```\n\n3. **`Math.sqrt(x)`**: Returns the square root of `x`.\n    ```javascript\n    document.write(\"sqrt(36) = \" + Math.sqrt(36) + \"\u003cbr\u003e\"); // Outputs: sqrt(36) = 6\n    ```\n\n4. **`Math.random()`**: Returns a random number between 0 (inclusive) and 1 (exclusive).\n    ```javascript\n    document.write(\"Random number: \" + Math.random() + \"\u003cbr\u003e\");\n    ```\n\n5. **`Math.floor(x)`**: Rounds `x` down to the nearest integer.\n    ```javascript\n    document.write(\"Floor of 5.7 is \" + Math.floor(5.7) + \"\u003cbr\u003e\"); // Outputs: Floor of 5.7 is 5\n    ```\n\n6. **`Math.ceil(x)`**: Rounds `x` up to the nearest integer.\n    ```javascript\n    document.write(\"Ceil of 5.3 is \" + Math.ceil(5.3) + \"\u003cbr\u003e\"); // Outputs: Ceil of 5.3 is 6\n    ```\n\n**Example:**\n```javascript\ndocument.write(\"2^9 = \" + Math.pow(2, 9) + \"\u003cbr\u003e\");\ndocument.write(\"abs(-34) = \" + Math.abs(-34) + \"\u003cbr\u003e\");\ndocument.write(\"sqrt(36) = \" + Math.sqrt(36) + \"\u003cbr\u003e\");\n```\n\n### String Functions\n\nJavaScript provides several built-in functions for string manipulation.\n\n1. **`length`**: Returns the length of the string.\n    ```javascript\n    var str1 = \"CodeWithHarry\";\n    document.write(str1.length + \"\u003cbr\u003e\"); // Outputs: 13\n    ```\n\n2. **`indexOf(substring)`**: Returns the index of the first occurrence of the specified substring.\n    ```javascript\n    document.write(str1.indexOf(\"With\") + \"\u003cbr\u003e\"); // Outputs: 4\n    ```\n\n3. **`toLowerCase()`**: Converts the string to lowercase.\n    ```javascript\n    document.write(str1.toLowerCase() + \"\u003cbr\u003e\"); // Outputs: codewithharry\n    ```\n\n4. **`toUpperCase()`**: Converts the string to uppercase.\n    ```javascript\n    document.write(str1.toUpperCase() + \"\u003cbr\u003e\"); // Outputs: CODEWITHHARRY\n    ```\n\n5. **`substring(start, end)`**: Extracts characters from `start` to `end`.\n    ```javascript\n    document.write(str1.substring(0, 4) + \"\u003cbr\u003e\"); // Outputs: Code\n    ```\n\n6. **`replace(searchValue, newValue)`**: Replaces occurrences of `searchValue` with `newValue`.\n    ```javascript\n    document.write(str1.replace(\"With\", \"Without\") + \"\u003cbr\u003e\"); // Outputs: CodeWithoutHarry\n    ```\n\n**Example:**\n```javascript\nvar str1 = \"CodeWithHarry\";\ndocument.write(str1.length + \"\u003cbr\u003e\"); // Outputs: 13\ndocument.write(str1.indexOf(\"With\") + \"\u003cbr\u003e\"); // Outputs: 4\ndocument.write(str1.toLowerCase() + \"\u003cbr\u003e\"); // Outputs: codewithharry\n```\n\n### Logical Operators\n\nLogical operators are used to combine conditional statements.\n\n| Operator | Name | Example               | Result                                     |\n|----------|------|-----------------------|--------------------------------------------|\n| `\u0026\u0026`     | AND  | `x \u0026\u0026 y`              | `true` if both `x` and `y` are true       |\n| `||`     | OR   | `x || y`              | `true` if either `x` or `y` is true       |\n| `!`      | NOT  | `!x`                  | `true` if `x` is not true                 |\n| `\u0026`      | Bitwise AND  | `x \u0026 y`      | Performs a bitwise AND on `x` and `y`      |\n| `|`      | Bitwise OR   | `x | y`      | Performs a bitwise OR on `x` and `y`       |\n| `^`      | Bitwise XOR  | `x ^ y`      | Performs a bitwise XOR on `x` and `y`      |\n\n**Examples:**\n```javascript\nvar myVar = (true \u0026\u0026 false);\ndocument.write(\"\u003cbr\u003e\");\ndocument.write(\"The value of (true \u0026\u0026 false) is \" + myVar + \"\u003cbr\u003e\"); // Outputs: false\n\nmyVar = (true || false);\ndocument.write(\"The value of (true || false) is \" + myVar + \"\u003cbr\u003e\"); // Outputs: true\n\nmyVar = (!true);\ndocument.write(\"The value of (!true) is \" + myVar + \"\u003cbr\u003e\"); // Outputs: false\n```\n\n---\n\n## Control Structures\n\nControl structures allow you to dictate the flow of your program based on certain conditions or repeated actions.\n\n### If-Else Conditions\n\nConditional statements allow you to perform different actions based on different conditions.\n\n**Example with Logical Operators:**\n```javascript\nvar age = prompt(\"What is your age?\");\n\nif (age \u003c 20 \u0026\u0026 age \u003e= 10) {\n    document.write(\"You go to the school.\u003cbr\u003e\");\n} else if (age \u003c 10 \u0026\u0026 age \u003e 3) {\n    document.write(\"You also go to the school.\u003cbr\u003e\");\n} else {\n    document.write(\"Do whatever you want.\u003cbr\u003e\");\n}\n```\n\n**Explanation:**\n- Checks if `age` is between 10 and 19.\n- If not, checks if `age` is between 4 and 9.\n- Otherwise, executes the `else` block.\n\n### Switch Statements\n\nSwitch statements execute different parts of code based on the value of a variable.\n\n**Example:**\n```javascript\nvar age = prompt(\"What is your age?\");\nswitch(age) {\n    case \"22\":\n        document.write(\"22 years old.. okay\u003cbr\u003e\");\n        break;\n    case \"21\":\n        document.write(\"21 years old.. okay\u003cbr\u003e\");\n        break;\n    case \"12\":\n        document.write(\"12 years old.. okay\u003cbr\u003e\");\n        break;\n    default:\n        document.write(\"Default age.. okay\u003cbr\u003e\");\n        break;\t\t\t\n}\n```\n\n**Explanation:**\n- Compares `age` with each `case`.\n- Executes the matching case block.\n- The `default` case executes if no match is found.\n\n**Note:** It's good practice to include `break` statements to prevent \"fall-through\" unless intentional.\n\n---\n\n## Loops\n\nLoops are used to execute a block of code multiple times until a specified condition is met. JavaScript supports several types of loops, each suited for different scenarios.\n\n### While Loop\n\nExecutes the block of code as long as the specified condition is `true`.\n\n**Example:**\n```javascript\nvar i = 1;\nwhile(i \u003c= 100) {\n    document.write(i + \"\u003cbr\u003e\");\n    i++;\n}\n```\n\n**Explanation:**\n- Initializes `i` to 1.\n- Continues to write `i` and increment until `i` exceeds 100.\n\n### Do-While Loop\n\nExecutes the block of code **once** before checking the condition. Continues to execute as long as the condition is `true`.\n\n**Example:**\n```javascript\nvar i = 101;\ndo {\n    document.write(i + \"\u003cbr\u003e\");\n    i++;\n} while(i \u003c= 100);\n```\n\n**Explanation:**\n- Executes the loop body once.\n- Checks the condition `i \u003c= 100` after the first iteration.\n- In this case, the loop runs only once since `i` starts at 101.\n\n### For Loop\n\nUsed when the number of iterations is known beforehand.\n\n**Example:**\n```javascript\nfor (var i = 0; i \u003c 2; i++) {\n    document.write(i + \"\u003cbr\u003e\");\n}\n```\n\n**Explanation:**\n- Initializes `i` to 0.\n- Continues to loop as long as `i` is less than 2.\n- Increments `i` by 1 after each iteration.\n\n### For...of and For...in Loops\n\n**For...of:** Iterates over iterable objects like arrays, strings, etc.\n\n**Example:**\n```javascript\nvar books = [\"Harry Potter\", \"NCERT\", \"CTCI\", 65];\n\nfor (var book of books) {\n    document.write(book + \"\u003cbr\u003e\");\n}\n```\n\n**For...in:** Iterates over enumerable properties of an object.\n\n**Example:**\n```javascript\nvar person = {name: \"Alice\", age: 25, city: \"New York\"};\n\nfor (var key in person) {\n    document.write(key + \": \" + person[key] + \"\u003cbr\u003e\");\n}\n```\n\n**Explanation:**\n- **For...of** is ideal for arrays and other iterable collections.\n- **For...in** is best suited for objects to access their properties.\n\n---\n\n## Arrays\n\nArrays are used to store multiple values in a single variable. They can hold elements of different data types and offer various methods to manipulate data.\n\n### Indexed Arrays\n\nIndexed arrays use numerical indexes starting from 0.\n\n**Example:**\n```javascript\nvar languages = [\"Python\", \"C++\", \"JavaScript\", \"Node.js\"];\ndocument.write(languages[0] + \"\u003cbr\u003e\"); // Outputs: Python\ndocument.write(\"Number of languages: \" + languages.length + \"\u003cbr\u003e\"); // Outputs: 4\n```\n\n**Common Array Methods:**\n\n1. **`push(element)`**: Adds an element to the end of the array.\n    ```javascript\n    languages.push(\"React\");\n    ```\n\n2. **`pop()`**: Removes the last element from the array.\n    ```javascript\n    languages.pop();\n    ```\n\n3. **`shift()`**: Removes the first element from the array.\n    ```javascript\n    languages.shift();\n    ```\n\n4. **`unshift(element)`**: Adds an element to the beginning of the array.\n    ```javascript\n    languages.unshift(\"Ruby\");\n    ```\n\n5. **`splice(index, deleteCount, item1, item2, ...)`**: Adds/removes elements at a specific index.\n    ```javascript\n    languages.splice(2, 1, \"TypeScript\"); // Replaces \"JavaScript\" with \"TypeScript\"\n    ```\n\n6. **`slice(start, end)`**: Returns a shallow copy of a portion of the array.\n    ```javascript\n    var selectedLanguages = languages.slice(1, 3);\n    ```\n\n7. **`forEach(callback)`**: Executes a provided function once for each array element.\n    ```javascript\n    languages.forEach(function(language) {\n        document.write(language + \"\u003cbr\u003e\");\n    });\n    ```\n\n### Associative Arrays (Objects)\n\nJavaScript does not have traditional associative arrays. Instead, objects are used to store key-value pairs.\n\n**Example:**\n```javascript\nvar ages = {\n    \"Peter\": 35,\n    \"Ben\": 37,\n    \"Joe\": 43\n};\n\ndocument.write(\"Peter is \" + ages.Peter + \" years old.\u003cbr\u003e\"); // Outputs: Peter is 35 years old.\n```\n\n**Accessing Object Properties:**\n- **Dot Notation:**\n    ```javascript\n    console.log(ages.Peter); // Outputs: 35\n    ```\n- **Bracket Notation:**\n    ```javascript\n    console.log(ages[\"Ben\"]); // Outputs: 37\n    ```\n\n**Example with Object Methods:**\n```javascript\nvar person = {\n    name: \"Alice\",\n    age: 25,\n    greet: function() {\n        return \"Hello, \" + this.name;\n    }\n};\n\ndocument.write(person.greet() + \"\u003cbr\u003e\"); // Outputs: Hello, Alice\n```\n\n**Explanation:**\n- `person` is an object with properties `name`, `age`, and a method `greet`.\n- The `greet` method returns a greeting message using the object's `name` property.\n\n### Multidimensional Arrays\n\nArrays containing one or more arrays.\n\n**Example:**\n```javascript\nvar contacts = [\n    [\"John Doe\", \"john@example.com\"],\n    [\"Jane Smith\", \"jane@example.com\"],\n    [\"Bob Johnson\", \"bob@example.com\"]\n];\n\ndocument.write(contacts[0][0] + \" - \" + contacts[0][1] + \"\u003cbr\u003e\"); // Outputs: John Doe - john@example.com\n```\n\n**Explanation:**\n- `contacts` is an array of arrays, each representing a contact's name and email.\n- Access elements using multiple indices.\n\n---\n\n## Functions\n\nFunctions are reusable blocks of code that perform specific tasks. They help in organizing code, making it modular and maintainable.\n\n### Function Declaration\n\nA standard way to define a function.\n\n**Example:**\n```javascript\nfunction greet() {\n    document.write(\"We are calling the greet function.\u003cbr\u003e\");\n    console.log(\"We have executed the greet function.\");\n}\n\ngreet();\ngreet();\ngreet();\ngreet();\n```\n\n**Explanation:**\n- **`function greet()`**: Declares a function named `greet`.\n- **Function Body:** Contains the code to be executed when the function is called.\n- **Calling the Function:** Executes the function's code block.\n\n### Function Expressions\n\nAssigning a function to a variable.\n\n**Example:**\n```javascript\nvar greet = function(name) {\n    return \"Hello, \" + name + \"!\";\n};\n\ndocument.write(greet(\"Alice\") + \"\u003cbr\u003e\"); // Outputs: Hello, Alice!\n```\n\n**Explanation:**\n- **Anonymous Function:** The function has no name and is assigned to the variable `greet`.\n- **Calling the Function:** `greet(\"Alice\")` executes the function and returns the greeting message.\n\n### Arrow Functions\n\nIntroduced in ES6, they provide a shorter syntax for writing functions.\n\n**Example:**\n```javascript\nconst add = (a, b) =\u003e a + b;\ndocument.write(\"5 + 10 = \" + add(5, 10) + \"\u003cbr\u003e\"); // Outputs: 5 + 10 = 15\n```\n\n**Explanation:**\n- **`const add = (a, b) =\u003e a + b;`**: Defines an arrow function that adds two numbers.\n- **Implicit Return:** If the function body has a single expression, it returns the result automatically.\n- **No `this` Binding:** Arrow functions do not have their own `this`.\n\n**Example with Multiple Statements:**\n```javascript\nconst multiply = (a, b) =\u003e {\n    let result = a * b;\n    return result;\n};\n\ndocument.write(\"5 * 10 = \" + multiply(5, 10) + \"\u003cbr\u003e\"); // Outputs: 5 * 10 = 50\n```\n\n**Explanation:**\n- When using curly braces `{}`, you must explicitly use `return` to return a value.\n\n### Higher-Order Functions\n\nFunctions that take other functions as arguments or return functions.\n\n**Example:**\n```javascript\nfunction operate(a, b, operation) {\n    return operation(a, b);\n}\n\nfunction subtract(a, b) {\n    return a - b;\n}\n\ndocument.write(\"10 - 5 = \" + operate(10, 5, subtract) + \"\u003cbr\u003e\"); // Outputs: 10 - 5 = 5\n```\n\n**Explanation:**\n- **`operate`**: A higher-order function that takes two numbers and an operation function.\n- **`subtract`**: A function that subtracts two numbers.\n- **Usage:** Passes the `subtract` function as an argument to `operate`.\n\n### Callback Functions\n\nFunctions passed as arguments to other functions, often used for asynchronous operations.\n\n**Example:**\n```javascript\nfunction fetchData(callback) {\n    setTimeout(() =\u003e {\n        const data = \"Data fetched from server.\";\n        callback(data);\n    }, 2000);\n}\n\nfunction displayData(data) {\n    document.write(data + \"\u003cbr\u003e\");\n}\n\nfetchData(displayData); // After 2 seconds, outputs: Data fetched from server.\n```\n\n**Explanation:**\n- **`fetchData`**: Simulates an asynchronous data fetch and calls the `callback` function with the data.\n- **`displayData`**: A callback function that displays the fetched data.\n- **Usage:** Passes `displayData` as an argument to `fetchData`.\n\n---\n\n## DOM Manipulation\n\n**Document Object Model (DOM)** allows JavaScript to interact with and manipulate HTML elements dynamically.\n\n### Selecting Elements\n\n1. **`getElementById(id)`**\n    ```javascript\n    var element = document.getElementById('th');\n    element.innerHTML = \"New content.\";\n    ```\n\n2. **`getElementsByClassName(className)`**\n    ```javascript\n    var elements = document.getElementsByClassName('myClass');\n    for(var i = 0; i \u003c elements.length; i++) {\n        elements[i].style.color = \"blue\";\n    }\n    ```\n\n3. **`querySelector(selector)`**\n    ```javascript\n    var element = document.querySelector('.myClass');\n    element.style.backgroundColor = \"yellow\";\n    ```\n\n4. **`querySelectorAll(selector)`**\n    ```javascript\n    var elements = document.querySelectorAll('p');\n    elements.forEach(function(element) {\n        element.style.fontSize = \"18px\";\n    });\n    ```\n\n### Modifying Elements\n\n1. **Changing Content:**\n    ```javascript\n    document.getElementById('th').innerHTML = \"Updated paragraph.\";\n    ```\n\n2. **Changing Styles:**\n    ```javascript\n    document.getElementById('th').style.color = \"red\";\n    ```\n\n3. **Adding/Removing Classes:**\n    ```javascript\n    var element = document.getElementById('th');\n    element.classList.add('active');\n    element.classList.remove('inactive');\n    ```\n\n4. **Creating New Elements:**\n    ```javascript\n    var newDiv = document.createElement('div');\n    newDiv.innerHTML = \"This is a new div.\";\n    document.body.appendChild(newDiv);\n    ```\n\n5. **Removing Elements:**\n    ```javascript\n    var element = document.getElementById('th');\n    element.parentNode.removeChild(element);\n    ```\n\n### Event Handling\n\nResponding to user interactions like clicks, hovers, etc.\n\n**Example:**\n```html\n\u003cbutton id=\"myButton\"\u003eClick Me\u003c/button\u003e\n\u003cscript\u003e\n    var button = document.getElementById('myButton');\n    button.addEventListener('click', function() {\n        alert(\"Button was clicked!\");\n    });\n\u003c/script\u003e\n```\n\n**Explanation:**\n- **`addEventListener`**: Attaches an event handler to the specified element.\n- **Event Types:** `click`, `mouseover`, `mouseout`, `keydown`, `keyup`, etc.\n\n**Example with Input Event:**\n```html\n\u003cinput type=\"text\" id=\"inputField\" placeholder=\"Type something...\"\u003e\n\u003cp id=\"output\"\u003e\u003c/p\u003e\n\n\u003cscript\u003e\n    var input = document.getElementById('inputField');\n    var output = document.getElementById('output');\n\n    input.addEventListener('input', function() {\n        output.innerHTML = input.value;\n    });\n\u003c/script\u003e\n```\n\n**Explanation:**\n- Updates the paragraph in real-time as the user types in the input field.\n\n---\n\n## Error Handling\n\nHandling errors gracefully ensures a better user experience and aids in debugging.\n\n### Try-Catch-Finally\n\n**Syntax:**\n```javascript\ntry {\n    // Code that may throw an error\n    throw new Error(\"Something went wrong!\");\n} catch (error) {\n    // Code to handle the error\n    console.log(error.message);\n} finally {\n    // Code that runs regardless of the outcome\n    console.log(\"This runs no matter what.\");\n}\n```\n\n**Explanation:**\n- **`try` Block:** Contains code that might throw an error.\n- **`catch` Block:** Executes if an error occurs in the `try` block.\n- **`finally` Block:** Executes after `try` and `catch`, regardless of the result.\n\n### Throwing Errors\n\n**Example:**\n```javascript\nfunction divide(a, b) {\n    if(b === 0) {\n        throw new Error(\"Division by zero is not allowed.\");\n    }\n    return a / b;\n}\n\ntry {\n    var result = divide(10, 0);\n    document.write(\"Result: \" + result + \"\u003cbr\u003e\");\n} catch (error) {\n    document.write(\"Error: \" + error.message + \"\u003cbr\u003e\");\n} finally {\n    document.write(\"Operation completed.\u003cbr\u003e\");\n}\n```\n\n**Explanation:**\n- **`throw` Statement:** Throws a custom error when attempting to divide by zero.\n- **Error Handling:** Catches and displays the error message without crashing the program.\n\n### Using `console.error()`\n\nLogs error messages to the console for debugging purposes.\n\n**Example:**\n```javascript\ntry {\n    // Code that may throw an error\n    nonExistentFunction();\n} catch (error) {\n    console.error(\"An error occurred:\", error);\n}\n```\n\n**Explanation:**\n- **`console.error()`**: Displays error messages in the browser's console with red color for visibility.\n\n---\n\n## Advanced JavaScript Concepts\n\nDelving into more complex topics enhances your understanding and ability to write efficient, maintainable code.\n\n### Closures\n\nA **closure** is a function that has access to its own scope, the outer function's scope, and the global scope.\n\n**Example:**\n```javascript\nfunction outerFunction() {\n    var outerVariable = \"I'm outside!\";\n\n    function innerFunction() {\n        console.log(outerVariable);\n    }\n\n    return innerFunction;\n}\n\nvar myFunction = outerFunction();\nmyFunction(); // Outputs: I'm outside!\n```\n\n**Explanation:**\n- **`outerFunction`** defines a variable and an inner function.\n- **`innerFunction`** has access to `outerVariable` even after `outerFunction` has finished executing.\n- This demonstrates closure, where the inner function retains access to the outer function's variables.\n\n**Use Cases:**\n- Data privacy and encapsulation.\n- Creating factory functions.\n- Partial application and function currying.\n\n### Hoisting\n\n**Hoisting** is JavaScript's default behavior of moving declarations to the top of the current scope before code execution.\n\n**Example:**\n```javascript\nconsole.log(a); // Outputs: undefined\nvar a = 10;\nconsole.log(a); // Outputs: 10\n```\n\n**Explanation:**\n- Due to hoisting, the variable declaration `var a;` is moved to the top.\n- However, the assignment `a = 10;` remains in place.\n- Before assignment, `a` is `undefined`.\n\n**Function Hoisting:**\n```javascript\ngreet(); // Outputs: Hello!\n\nfunction greet() {\n    console.log(\"Hello!\");\n}\n```\n\n**Explanation:**\n- Function declarations are hoisted entirely, allowing them to be called before their definition.\n\n**Function Expressions and Hoisting:**\n```javascript\ngreet(); // TypeError: greet is not a function\n\nvar greet = function() {\n    console.log(\"Hello!\");\n};\n```\n\n**Explanation:**\n- Only the variable declaration `var greet;` is hoisted, not the assignment.\n- Attempting to call `greet()` before assignment results in an error.\n\n### Prototype and Inheritance\n\nJavaScript uses prototypes for inheritance, allowing objects to inherit properties and methods from other objects.\n\n**Example:**\n```javascript\nfunction Person(name, age) {\n    this.name = name;\n    this.age = age;\n}\n\nPerson.prototype.greet = function() {\n    console.log(\"Hello, my name is \" + this.name);\n};\n\nvar alice = new Person(\"Alice\", 25);\nalice.greet(); // Outputs: Hello, my name is Alice\n```\n\n**Explanation:**\n- **Constructor Function:** `Person` initializes new objects with `name` and `age`.\n- **Prototype Method:** `greet` is added to `Person`'s prototype, making it available to all instances.\n- **Inheritance:** `alice` inherits the `greet` method from `Person.prototype`.\n\n**Prototypal Inheritance:**\n```javascript\nfunction Employee(name, age, role) {\n    Person.call(this, name, age);\n    this.role = role;\n}\n\nEmployee.prototype = Object.create(Person.prototype);\nEmployee.prototype.constructor = Employee;\n\nEmployee.prototype.work = function() {\n    console.log(this.name + \" is working as a \" + this.role);\n};\n\nvar bob = new Employee(\"Bob\", 30, \"Developer\");\nbob.greet(); // Outputs: Hello, my name is Bob\nbob.work();  // Outputs: Bob is working as a Developer\n```\n\n**Explanation:**\n- **Inheritance Chain:** `Employee` inherits from `Person`, gaining access to `greet`.\n- **Additional Methods:** `work` is specific to `Employee` instances.\n\n### Event Loop and Asynchronous JavaScript\n\nUnderstanding the **event loop** is crucial for managing asynchronous operations in JavaScript.\n\n**Event Loop:** A mechanism that handles asynchronous callbacks. It allows JavaScript to perform non-blocking operations despite being single-threaded.\n\n**Example with Promises:**\n```javascript\nconsole.log(\"Start\");\n\nsetTimeout(function() {\n    console.log(\"Inside setTimeout\");\n}, 0);\n\nPromise.resolve().then(function() {\n    console.log(\"Inside Promise\");\n});\n\nconsole.log(\"End\");\n```\n\n**Output:**\n```\nStart\nEnd\nInside Promise\nInside setTimeout\n```\n\n**Explanation:**\n- **Synchronous Code:** Executes first (`Start`, `End`).\n- **Promises:** Microtasks executed after the current stack but before macrotasks.\n- **`setTimeout`:** Macrotask executed after microtasks.\n\n### Asynchronous JavaScript: Promises and Async/Await\n\n**Promises:** Represent the eventual completion or failure of an asynchronous operation.\n\n**Example with Promises:**\n```javascript\nfunction fetchData() {\n    return new Promise(function(resolve, reject) {\n        setTimeout(function() {\n            const data = \"Data fetched successfully.\";\n            resolve(data);\n        }, 2000);\n    });\n}\n\nfetchData().then(function(data) {\n    console.log(data);\n}).catch(function(error) {\n    console.error(error);\n});\n```\n\n**Explanation:**\n- **`fetchData` Function:** Returns a promise that resolves after 2 seconds.\n- **`.then` Method:** Handles the resolved value.\n- **`.catch` Method:** Handles any errors.\n\n**Async/Await:** Syntactic sugar over Promises, making asynchronous code look synchronous.\n\n**Example with Async/Await:**\n```javascript\nasync function getData() {\n    try {\n        const data = await fetchData();\n        console.log(data);\n    } catch(error) {\n        console.error(error);\n    }\n}\n\ngetData();\n```\n\n**Explanation:**\n- **`async` Function:** Allows the use of `await` inside it.\n- **`await` Keyword:** Pauses the function execution until the promise is resolved.\n- **Error Handling:** Use `try-catch` blocks to handle errors.\n\n**Using Fetch API with Async/Await:**\n```javascript\nasync function fetchUserData() {\n    try {\n        const response = await fetch('https://jsonplaceholder.typicode.com/users/1');\n        const user = await response.json();\n        console.log(user);\n    } catch(error) {\n        console.error(\"Error fetching user data:\", error);\n    }\n}\n\nfetchUserData();\n```\n\n**Explanation:**\n- **`fetch` Function:** Makes an HTTP request.\n- **`await` Keywords:** Wait for the response and then parse it as JSON.\n- **Error Handling:** Catches any network or parsing errors.\n\n---\n\n## Node.js\n\n**Node.js** is a powerful JavaScript runtime built on Chrome's V8 engine, enabling JavaScript to run outside the browser. It is essential for server-side development, building scalable network applications, and managing project dependencies.\n\n### Introduction to Node.js\n\n**Key Features:**\n- **Asynchronous and Event-Driven:** Handles multiple operations without blocking the execution.\n- **Single-Threaded:** Utilizes a single thread with non-blocking I/O calls for efficient performance.\n- **NPM (Node Package Manager):** Facilitates the installation and management of third-party libraries.\n- **Cross-Platform:** Runs on various operating systems, including Windows, macOS, and Linux.\n\n**Use Cases:**\n- **Web Servers:** Building APIs and web applications.\n- **Real-Time Applications:** Chat applications, live updates.\n- **Command-Line Tools:** Automating tasks and building utilities.\n- **Microservices:** Creating scalable, modular services.\n\n### Setting Up a Node.js Project\n\n**Steps:**\n\n1. **Initialize the Project:**\n    ```bash\n    mkdir my-node-project\n    cd my-node-project\n    npm init -y\n    ```\n\n    **Explanation:**\n    - **`mkdir my-node-project`**: Creates a new directory.\n    - **`cd my-node-project`**: Navigates into the directory.\n    - **`npm init -y`**: Initializes a new Node.js project with default settings, creating a `package.json` file.\n\n2. **Install Dependencies:**\n    - **Express.js:** A minimal and flexible Node.js web application framework.\n        ```bash\n        npm install express\n        ```\n\n3. **Create `index.js`:**\n    ```javascript\n    const express = require('express');\n    const app = express();\n    const port = 3000;\n\n    app.get('/', (req, res) =\u003e {\n        res.send('Hello, World from Node.js!');\n    });\n\n    app.listen(port, () =\u003e {\n        console.log(`Server is running at http://localhost:${port}`);\n    });\n    ```\n\n4. **Run the Server:**\n    ```bash\n    node index.js\n    ```\n\n5. **Access the Server:**\n    - Open your browser and navigate to `http://localhost:3000/`.\n    - You should see the message: **\"Hello, World from Node.js!\"**\n\n**Explanation:**\n- **`express` Module:** Imported to create a web server.\n- **`app.get('/', ...)`**: Defines a route for the root URL.\n- **`app.listen(port, ...)`**: Starts the server on the specified port.\n\n### Using npm (Node Package Manager)\n\n**npm** is integral to Node.js, managing dependencies and facilitating the use of third-party libraries.\n\n**Common npm Commands:**\n\n1. **Install a Package Locally:**\n    ```bash\n    npm install package-name\n    ```\n\n2. **Install a Package Globally:**\n    ```bash\n    npm install -g package-name\n    ```\n\n3. **Uninstall a Package:**\n    ```bash\n    npm uninstall package-name\n    ```\n\n4. **List Installed Packages:**\n    ```bash\n    npm list\n    npm list -g\n    ```\n\n5. **Update Packages:**\n    ```bash\n    npm update\n    ```\n\n6. **Run Scripts:**\n    - Defined in `package.json` under the `scripts` section.\n    ```bash\n    npm run script-name\n    ```\n\n**Example `package.json` Scripts Section:**\n```json\n\"scripts\": {\n    \"start\": \"node index.js\",\n    \"dev\": \"nodemon index.js\"\n}\n```\n\n**Usage:**\n- **`npm run start`**: Runs the `start` script.\n- **`npm run dev`**: Runs the `dev` script, typically using `nodemon` for automatic restarts on code changes.\n\n**Best Practices:**\n- **Use Semantic Versioning:** Follow the `MAJOR.MINOR.PATCH` format for versioning packages.\n- **Lock Dependencies:** Use `package-lock.json` to ensure consistent installations across environments.\n- **Avoid Global Installs for Project-Specific Packages:** Install packages locally unless they are command-line tools needed across projects.\n\n### Creating a Simple Server with Node.js\n\nBuilding a basic web server helps understand how Node.js handles HTTP requests and responses.\n\n**Example:**\n- **server.js**\n    ```javascript\n    const http = require('http');\n\n    const hostname = '127.0.0.1';\n    const port = 3000;\n\n    const server = http.createServer((req, res) =\u003e {\n        res.statusCode = 200;\n        res.setHeader('Content-Type', 'text/plain');\n        res.end('Hello, World!\\n');\n    });\n\n    server.listen(port, hostname, () =\u003e {\n        console.log(`Server running at http://${hostname}:${port}/`);\n    });\n    ```\n\n**Execution:**\n```bash\nnode server.js\n```\n\n**Accessing the Server:**\n- Open your browser and navigate to `http://127.0.0.1:3000/`.\n- You should see the message: **\"Hello, World!\"**\n\n**Explanation:**\n- **`http.createServer`**: Creates a new HTTP server.\n- **Request Listener:** Handles incoming requests and sends responses.\n- **`server.listen`**: Starts the server on the specified hostname and port.\n\n**Using Express.js for Enhanced Functionality:**\n\n**Example:**\n- **app.js**\n    ```javascript\n    const express = require('express');\n    const app = express();\n    const port = 3000;\n\n    app.get('/', (req, res) =\u003e {\n        res.send('Hello, World from Express!');\n    });\n\n    app.get('/about', (req, res) =\u003e {\n        res.send('About Page');\n    });\n\n    app.listen(port, () =\u003e {\n        console.log(`Express app listening at http://localhost:${port}`);\n    });\n    ```\n\n**Execution:**\n```bash\nnode app.js\n```\n\n**Accessing the Server:**\n- Navigate to `http://localhost:3000/` to see **\"Hello, World from Express!\"**\n- Navigate to `http://localhost:3000/about` to see **\"About Page\"**\n\n**Explanation:**\n- **Express.js:** Simplifies routing and server management.\n- **`app.get`**: Defines routes and their corresponding response handlers.\n\n---\n\n## Important Interview Topics\n\nPreparing for JavaScript job interviews requires a deep understanding of both fundamental and advanced concepts. Focus on the following key areas to excel in your interviews:\n\n1. **Scope and Closures:**\n   - **Scope:** Understanding global vs. local (function/block) scope.\n   - **Closures:** Functions retaining access to their lexical scope even when executed outside their original scope.\n   - **Example Question:** *What is a closure in JavaScript and how is it used?*\n\n2. **Hoisting:**\n   - **Variable and Function Hoisting:** How declarations are moved to the top of their scope.\n   - **Difference between `var`, `let`, and `const` in hoisting.\n   - **Example Question:** *Explain how hoisting works in JavaScript.*\n\n3. **Event Loop and Asynchronous JavaScript:**\n   - **Event Loop Mechanism:** How JavaScript handles asynchronous operations.\n   - **Promises and Async/Await:** Managing asynchronous code.\n   - **Callbacks and Callback Hell:** Handling nested asynchronous operations.\n   - **Example Question:** *Can you explain the JavaScript event loop and its role in asynchronous programming?*\n\n4. **Prototype and Inheritance:**\n   - **Prototypal Inheritance:** How objects inherit properties and methods.\n   - **Prototype Chain:** Accessing inherited properties.\n   - **Example Question:** *What is prototypal inheritance in JavaScript?*\n\n5. **`this` Keyword:**\n   - **Contextual Binding:** How `this` refers to different objects based on how a function is called.\n   - **Arrow Functions and `this`:** Differences in `this` binding.\n   - **Example Question:** *How does the `this` keyword work in JavaScript?*\n\n6. **ES6 Features:**\n   - **Let and Const:** Block-scoped variable declarations.\n   - **Arrow Functions:** Concise function syntax and lexical `this`.\n   - **Template Literals:** String interpolation and multi-line strings.\n   - **Destructuring:** Extracting data from arrays and objects.\n   - **Modules:** Importing and exporting code.\n   - **Example Question:** *What are the differences between `var`, `let`, and `const`?*\n\n7. **DOM Manipulation:**\n   - **Selecting and Modifying Elements:** Using selectors and altering content/styles.\n   - **Event Handling:** Responding to user interactions.\n   - **Example Question:** *How do you manipulate the DOM using JavaScript?*\n\n8. **Error Handling:**\n   - **Try-Catch:** Managing exceptions.\n   - **Custom Errors:** Creating and throwing custom error objects.\n   - **Example Question:** *How do you handle errors in JavaScript?*\n\n9. **Data Structures:**\n   - **Arrays, Objects, Maps, Sets:** Understanding different data structures and their use cases.\n   - **Example Question:** *What is the difference between an array and an object in JavaScript?*\n\n10. **Best Practices:**\n    - **Writing Clean and Efficient Code:** Avoiding global variables, using strict mode, etc.\n    - **Avoiding Common Pitfalls:** Understanding common bugs and how to prevent them.\n    - **Example Question:** *What are some best practices for writing maintainable JavaScript code?*\n\n**Sample Interview Questions:**\n\n- **What is a closure in JavaScript?**\n- **Explain the difference between `==` and `===` operators.**\n- **How does the event loop work in JavaScript?**\n- **What is hoisting, and how does it affect variable declarations?**\n- **Describe prototypal inheritance in JavaScript.**\n- **How do arrow functions differ from regular functions regarding the `this` keyword?**\n- **What are promises, and how do they work?**\n- **Explain the use of `async` and `await` in JavaScript.**\n- **How can you handle asynchronous operations in JavaScript?**\n- **What is the difference between `var`, `let`, and `const`?**\n\n**Preparation Tips:**\n- **Understand Concepts Deeply:** Don't just memorize definitions; understand how and why they work.\n- **Practice Coding:** Implement concepts through coding exercises and projects.\n- **Review Common Algorithms and Data Structures:** Familiarize yourself with sorting algorithms, searching techniques, and data structure manipulations.\n- **Mock Interviews:** Participate in mock interviews to simulate the interview environment.\n\n---\n\n## Best Documentation Resources\n\nTo deepen your understanding and stay updated with JavaScript advancements, refer to the following top-tier documentation and learning resources:\n\n1. **[MDN Web Docs - JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript)**\n   - Comprehensive and authoritative documentation on all JavaScript topics.\n   - Includes tutorials, references, guides, and best practices.\n   - Regularly updated with the latest language features.\n\n2. **[JavaScript.info](https://javascript.info/)**\n   - Modern JavaScript tutorial with in-depth explanations.\n   - Covers basics to advanced topics with interactive examples.\n   - Structured learning path for progressive understanding.\n\n3. **[W3Schools JavaScript Tutorial](https://www.w3schools.com/js/)**\n   - Beginner-friendly tutorials with interactive coding examples.\n   - Covers fundamental concepts and provides quizzes for self-assessment.\n   - Easy-to-navigate sections for quick reference.\n\n4. **[ECMAScript Specification](https://tc39.es/ecma262/)**\n   - Official language specification for JavaScript.\n   - Detailed and technical, suitable for advanced learners and reference.\n   - Managed by TC39, the committee responsible for JavaScript standards.\n\n5. **[Stack Overflow JavaScript Questions](https://stackoverflow.com/questions/tagged/javascript)**\n   - Community-driven Q\u0026A platform.\n   - Solve coding issues, understand best practices, and learn from real-world problems.\n   - Engage with a vast community of developers for diverse perspectives.\n\n6. **[Eloquent JavaScript (Book)](https://eloquentjavascript.net/)**\n   - Free online book covering JavaScript concepts and programming techniques.\n   - Includes exercises and projects to reinforce learning.\n   - Well-suited for both beginners and experienced programmers.\n\n7. **[You Don't Know JS (Book Series)](https://github.com/getify/You-Dont-Know-JS)**\n   - In-depth book series exploring JavaScript's core mechanisms.\n   - Available for free on GitHub, with comprehensive coverage of advanced topics.\n   - Written by Kyle Simpson, a renowned JavaScript expert.\n\n8. **[FreeCodeCamp JavaScript Curriculum](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/)**\n   - Interactive learning platform with hands-on coding challenges.\n   - Covers a wide range of JavaScript topics, from basics to algorithms.\n   - Earn certifications upon completion of modules.\n\n9. **[Codecademy JavaScript Course](https://www.codecademy.com/learn/introduction-to-javascript)**\n   - Interactive courses with real-time feedback.\n   - Structured lessons covering syntax, functions, objects, and more.\n   - Paid and free content available.\n\n10. **[Udemy JavaScript Courses](https://www.udemy.com/topic/javascript/)**\n    - Extensive library of JavaScript courses catering to various skill levels.\n    - Video lectures, quizzes, and projects for practical learning.\n    - User reviews and ratings to select the best-suited courses.\n\n11. **[LeetCode JavaScript Problems](https://leetcode.com/problemset/all/?language=JavaScript)**\n    - Platform for practicing coding problems using JavaScript.\n    - Enhances problem-solving skills and algorithmic thinking.\n    - Suitable for preparing for technical interviews.\n\n12. **[JavaScript Weekly](https://javascriptweekly.com/)**\n    - A weekly newsletter delivering the latest JavaScript news, tutorials, and resources.\n    - Stay updated with the rapidly evolving JavaScript ecosystem.\n\n---\n\n## Conclusion\n\nThis study guide encompasses the fundamental and advanced aspects of JavaScript essential for your job exam and career growth. It covers basic syntax, variables, operators, control structures, functions, arrays, DOM manipulation, error handling, and crucial advanced topics like closures, prototypal inheritance, and asynchronous programming. Additionally, it introduces Node.js for server-side development and provides a thorough guide on setting up your development environment with Visual Studio Code.\n\n**Key Takeaways:**\n- **Master the Basics:** Ensure a solid understanding of JavaScript's core concepts.\n- **Practice Regularly:** Implement concepts through coding exercises and projects.\n- **Stay Updated:** Keep abreast of the latest JavaScript features and best practices.\n- **Prepare for Interviews:** Focus on important topics and practice answering common interview questions.\n- **Utilize Resources:** Leverage the best documentation and learning platforms to enhance your knowledge.\n\n**Final Advice:**\n- **Consistent Practice:** Regular coding and problem-solving reinforce your understanding.\n- **Build Projects:** Create small projects to apply what you've learned in real-world scenarios.\n- **Engage with the Community:** Participate in forums, contribute to open-source projects, and collaborate with other developers.\n- **Seek Feedback:** Review your code with peers or mentors to identify areas for improvement.\n\nGood luck with your studies and your upcoming job exam! Embrace the learning journey, and happy coding!\n\n---\n\n## Additional Resources\n\n- **[JavaScript Official Website](https://www.javascript.com/)**\n- **[Node.js Official Website](https://nodejs.org/)**\n- **[Express.js Official Website](https://expressjs.com/)**\n- **[Visual Studio Code Official Website](https://code.visualstudio.com/)**\n- **[GitHub JavaScript Projects](https://github.com/search?q=javascript)**\n- **[Frontend Masters JavaScript Courses](https://frontendmasters.com/learn/javascript/)**\n- **[Pluralsight JavaScript Path](https://www.pluralsight.com/paths/javascript)**\n\n---\n\n*Happy Coding!*\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fakashdip2001%2Fjavascript","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fakashdip2001%2Fjavascript","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fakashdip2001%2Fjavascript/lists"}