{"id":19606747,"url":"https://github.com/learnwithfair/javascript-documentation","last_synced_at":"2026-06-13T11:32:21.352Z","repository":{"id":237370720,"uuid":"794396035","full_name":"learnwithfair/javascript-documentation","owner":"learnwithfair","description":"javascript-documentation with  [learnwithfair, Learn with fair, Rahatul Rabbi, Md Rahatul Rabbi ,rahatulrabbi]","archived":false,"fork":false,"pushed_at":"2024-05-02T18:19:11.000Z","size":815,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-26T16:50:00.618Z","etag":null,"topics":["documentation","javascript","js","learn-with-fair","learnwithfair","rahatul-rabbi","rahatulrabbi","webdevelopment"],"latest_commit_sha":null,"homepage":"","language":null,"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/learnwithfair.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-05-01T04:02:18.000Z","updated_at":"2024-05-02T18:19:15.000Z","dependencies_parsed_at":"2024-05-01T05:23:39.032Z","dependency_job_id":"cff31f02-9453-40f9-b386-e44413d96f2e","html_url":"https://github.com/learnwithfair/javascript-documentation","commit_stats":null,"previous_names":["learnwithfair/javascript-documentation"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/learnwithfair/javascript-documentation","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learnwithfair%2Fjavascript-documentation","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learnwithfair%2Fjavascript-documentation/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learnwithfair%2Fjavascript-documentation/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learnwithfair%2Fjavascript-documentation/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/learnwithfair","download_url":"https://codeload.github.com/learnwithfair/javascript-documentation/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learnwithfair%2Fjavascript-documentation/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34283390,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-13T02:00:06.617Z","response_time":62,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":["documentation","javascript","js","learn-with-fair","learnwithfair","rahatul-rabbi","rahatulrabbi","webdevelopment"],"created_at":"2024-11-11T10:07:06.023Z","updated_at":"2026-06-13T11:32:21.314Z","avatar_url":"https://github.com/learnwithfair.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# JAVASCRIPT-DOCUMENTATION\n\nThanks for visiting my GitHub account!\n\n\u003cimg src =\"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTlhLpV7c7ZlQ69IaQrygUzN62Q4kB9dgOiyGaVQV_uglXLZ7DtWKuLBGvrpovgah7RNfo\u0026usqp=CAU\" /\u003e **JavaScript** is the most powerful and versatile programming language used in the web. It is a lightweight, cross-platform, single-threaded and interpreted programming language. It is a commonly used programming language to create dynamic and interactive elements in web applications. It is easy to learn, compiled language. [more](https://www.w3schools.com/js/)\n\n- JavaScript is the world's most popular programming language.\n- JavaScript is the programming language of the Web.\n- JavaScript is easy to learn.\n\n### [Code-Example](https://github.com/learnwithfair/java-script)\n\n## Source Code (Download)\n\n[Click Here](https://mega.nz/folder/RGFiUApD#PoKIVCwF8IkQhE2PHw1XxQ)\n\n## Required Software (Download)\n\n- VS Code, Download -\u003ehttps://code.visualstudio.com/download\n\n## Project Roadmap\n\n|                                |\n| :----------------------------: |\n|            Roadmap             |\n| ![roadmap](images/roadmap.png) |\n\n## Mistakes\n\n|                                    |                                    |\n| :--------------------------------: | :--------------------------------: |\n|      ![roadmap](images/0.jpg)      |      ![roadmap](images/1.jpg)      |\n|      ![roadmap](images/2.jpg)      |      ![roadmap](images/3.jpg)      |\n|      ![roadmap](images/4.jpg)      |      ![roadmap](images/5.jpg)      |\n|      ![roadmap](images/6.jpg)      |      ![roadmap](images/7.jpg)      |\n| ![roadmap](images/simple-code.jpg) | ![roadmap](images/status-code.jpg) |\n\n## Table of Contents\n\n1. [Basic Javascript Topics](#1-basic-javascript-topics)\n\n   [1.1 Introduction to Javascript](#11-introduction-to-javascript)\n\n   [1.2 Output Console Object \u0026 comment](#12-output--comment)\n\n   [1.3 Tokens - variables, data types, operators](#13-tokens)\n\n   [1.4 Control Flow](#14-control-statement)\n\n   [1.5 Function](#15-function---traditional)\n\n   [1.6 Hositing, scope of variables and closures](#16-hoisting-scope-of-variables--closures)\n\n   - [1.6.1 Hositings](#161-hoisting)\n   - [1.6.2 Scope of variables and closures](#162-scope-and-closures)\n   - [1.6.3 var, let, const](#163-var-let-const)\n\n   [1.7 Objects](#17-objects)\n\n   [1.8 Arrays](#18-arrays)\n\n   [1.9 Built-in methods](#19-built-in-methods)\n\n   [1.10 Error Handling](#110-errors-and-errors-handling)\n\n   [1.11 JSON and JSDoc](#111-json-and-jsdoc)\n\n2. [Intermediate JavaScript Topics](#2-intermediate-javascript-topics)\n\n   [2.1 Document Object Model (DOM) and Events](#21-document-object-model-dom-and-events)\n\n   [2.2 Browser Object Model (BOM)](#22-browser-object-model-bom)\n\n   [2.3 Local storage](#23-local-storage)\n\n   [2.4 ES6 Features](#24-es6-features)\n\n   [2.5 Higher order and callback functions](#25-higher-order-and-callback-functions)\n\n   [2.6 Best Practices](#26-best-practices)\n\n   [2.7 npm \u0026 ESLint setup](#27-npm--eslint-setup)\n\n   [2.8 You must know](#28-you-must-know)\n   [2.9 API Calling](#29-api-calling)\n\n3. [Advanced JavaScript Topics](#3-advanced-javascript-topics)\n   [3.1 OOP](#31-object-oriented-programming-oop)\n   [3.2 Bank Demo](#32-bank-demo)\n   [3.3 Prepare for technical test](#33-prepare-for-technical-test)\n   [3.2 Testing and Debugging]()\n\n   - [Unit testing with frameworks like Jest]()\n   - [Debugging tools and techniques]()\n\n   [3.3 Security]()\n\n   - [Cross-Site Scripting (XSS) prevention]()\n   - [Cross-Site Request Forgery (CSRF) prevention]()\n   - [Content Security Policy (CSP)]()\n\n   [3.4 Performance Optimization]()\n\n   - [Code optimization]()\n   - [Network optimization (lazy loading, asset compression)]()\n   - [Rendering optimization (requestAnimationFrame)]()\n\n   [3.5 Design Patterns]()\n\n   - [Singleton pattern]()\n   - [Module pattern]()\n   - [Observer pattern]()\n   - [Factory pattern]()\n\n   [3.6 Project ideas]()\n\n   - Caclulator - basics, BMI\n   - Converter - Temperature\n   - guessing game, dynamic cards, user preference (youtube)\n   - API - Weather, Joke, Dog, Products\n   - [Todo CRUD APP](https://todo-crud-app-2023.netlify.app/)\n\n## 1. Basic Javascript Topics\n\n### 1.1 Introduction to Javascript\n\n- What is Javascript?\n\n  - A programming language for web.\n  - it can be used in front-end and back-end\n  - It adds interactivity to the web page such as adding items to the carts, form validation etc.\n  - Example: Create a button with HTML, Style with CSS and add clicking functionality by using javascript\n  - A demo\n\n    ```js\n\n        // index.html\n        \u003c!DOCTYPE html\u003e\n        \u003chtml lang=\"en\"\u003e\n          \u003chead\u003e\n            \u003cmeta charset=\"UTF-8\" /\u003e\n            \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /\u003e\n            \u003ctitle\u003eDocument\u003c/title\u003e\n            \u003clink rel=\"stylesheet\" href=\"test.css\" /\u003e\n          \u003c/head\u003e\n          \u003cbody\u003e\n            \u003ch1\u003eWelcome to JS\u003c/h1\u003e\n            \u003cbutton onclick=\"deleteItem()\"\u003eDelete\u003c/button\u003e\n          \u003c/body\u003e\n        \u003c/html\u003e\n\n        // style.css\n        button {\n          background-color: green;\n          color: white;\n          padding: 0.5rem;\n          border: none;\n          border-radius: 5px 5px;\n        }\n\n        // index.js\n        function deleteItem() {\n          alert(\"The item is deleted!\");\n        }\n\n    ```\n\n- What are the ways to add javascript?\n\n  - **Inline JavaScript:**\n\n    Inline JavaScript is directly embedded within an HTML document using the `\u003cscript\u003e` tag. It's placed directly within the HTML code and typically used for small scripts or quick actions.\n\n    ```html\n    \u003c!DOCTYPE html\u003e\n    \u003chtml\u003e\n      \u003chead\u003e\n        \u003ctitle\u003eInline JavaScript Example\u003c/title\u003e\n      \u003c/head\u003e\n      \u003cbody\u003e\n        \u003ch1\u003eWelcome to JS\u003c/h1\u003e\n        \u003cbutton onclick=\"alert('The item is deleted!')\"\u003eDelete\u003c/button\u003e\n      \u003c/body\u003e\n    \u003c/html\u003e\n    ```\n\n    In this example, the JavaScript code `alert('The item is deleted!')` is executed when the button is clicked.\n\n  - **Internal JavaScript:**\n\n    Internal JavaScript is placed within the HTML document, but it's placed in the `\u003cscript\u003e` tag within the `\u003chead\u003e` or `\u003cbody\u003e` section of the HTML. This allows you to keep your JavaScript separate from your HTML content.\n\n    ```html\n    \u003c!DOCTYPE html\u003e\n    \u003chtml\u003e\n      \u003chead\u003e\n        \u003ctitle\u003eInternal JavaScript Example\u003c/title\u003e\n        \u003cscript\u003e\n          function deleteItem() {\n            alert(\"The item is deleted!\");\n          }\n        \u003c/script\u003e\n      \u003c/head\u003e\n      \u003cbody\u003e\n        \u003ch1\u003eInternal JavaScript Example\u003c/h1\u003e\n\n        \u003cbutton onclick=\"deleteItem()\"\u003eDelete\u003c/button\u003e\n      \u003c/body\u003e\n    \u003c/html\u003e\n    ```\n\n    In this example, the JavaScript function `deleteItem()` is defined within the `\u003cscript\u003e` tag in the HTML document and called when the button is clicked.\n\n  - **External JavaScript:**\n\n    External JavaScript is stored in a separate .js file and linked to the HTML document using the `\u003cscript\u003e` tag's `src` attribute. **This approach is ideal for larger scripts and helps keep your HTML clean and organized.**\n\n    **index.html:**\n\n    ```html\n    \u003c!DOCTYPE html\u003e\n    \u003chtml\u003e\n      \u003chead\u003e\n        \u003ctitle\u003eExternal JavaScript Example\u003c/title\u003e\n      \u003c/head\u003e\n      \u003cbody\u003e\n        \u003ch1\u003eExternal JavaScript Example\u003c/h1\u003e\n\n        \u003cbutton onclick=\"deleteItem()\"\u003eClick Me\u003c/button\u003e\n        \u003cscript src=\"script.js\"\u003e\u003c/script\u003e\n        \u003cscript src=\"script2.js\"\u003e\u003c/script\u003e\n      \u003c/body\u003e\n    \u003c/html\u003e\n    ```\n\n    **script.js:**\n\n    ```javascript\n    function deleteItem() {\n      alert(\"The item is deleted!\");\n    }\n    ```\n\n    In this example, the JavaScript code is stored in an external file named `script.js` and linked to the HTML file using the `\u003cscript\u003e` tag's `src` attribute.\n\n    External JavaScript is often preferred for better code organization and maintainability, especially in larger web applications where you may have multiple scripts.\n\n### 1.2 Output \u0026 comment\n\n- output functions: functions that will help you to show output such as document.write(), window global object -\u003e console.log(), lert(), confirm()\n- console\n\n  - In JavaScript, the `console` object is a built-in object that provides a way to interact with the browser's debugging console or the console of other JavaScript environments (like Node.js). It's commonly used for debugging, logging information, and monitoring the behavior of your code. Here are some important functions and methods provided by the `console` object:\n\n    1. **`console.log(...args)`**: This is one of the most commonly used functions. It logs the provided arguments to the console. For example:\n\n       ```javascript\n       console.log(\"Hello, world!\");\n       ```\n\n    2. **`console.error(...args)`**: Logs error messages to the console with a red icon. Useful for reporting errors and issues in your code.\n\n       ```javascript\n       console.error(\"An error occurred.\");\n       ```\n\n    3. **`console.warn(...args)`**: Logs warning messages to the console with a yellow icon. It's often used for non-fatal issues or potential problems.\n\n       ```javascript\n       console.warn(\"This is a warning message.\");\n       ```\n\n    4. **`console.info(...args)`**: Logs informational messages to the console with a blue icon. Useful for general information about your code's behavior.\n\n       ```javascript\n       console.info(\"This is an informational message.\");\n       ```\n\n    5. **`console.debug(...args)`**: Logs debugging messages to the console. These messages are typically used for detailed debugging information and may not be shown in all console environments.\n\n       ```javascript\n       console.debug(\"Debugging information.\");\n       ```\n\n    6. **`console.clear()`**: Clears the console, removing all previous log messages. Useful for keeping the console tidy during debugging sessions.\n\n       ```javascript\n       console.clear();\n       ```\n\n    7. **`console.group(label)`** and **`console.groupEnd()`**: These methods allow you to group related log messages together. You can create a group using `console.group(label)` and close it with `console.groupEnd()`. This is particularly useful for organizing logs in complex applications.\n\n       ```javascript\n       console.group(\"Group Label\");\n       console.log(\"Log message 1\");\n       console.log(\"Log message 2\");\n       console.groupEnd();\n       ```\n\n    8. **`console.table(data)`**: Displays tabular data in a table format. This is especially helpful for visualizing arrays or objects.\n\n       ```javascript\n       const data = [\n         { name: \"Alice\", age: 30 },\n         { name: \"Bob\", age: 25 },\n       ];\n       console.table(data);\n       ```\n\n    9. **`console.time(label)`** and **`console.timeEnd(label)`**: These methods are used to measure the time it takes to execute a piece of code. You start a timer with `console.time(label)` and stop it with `console.timeEnd(label)`.\n\n       ```javascript\n       console.time(\"Timer\");\n       // Code to measure execution time\n       console.timeEnd(\"Timer\");\n       ```\n\n- Comments in JavaScript are used to provide explanations or additional information within your code. They are not executed by the JavaScript interpreter and are meant for human readability. JavaScript supports two primary types of comments:\n\n  1. **Single-line Comments**:\n\n     - Denoted by `//`.\n     - Anything following `//` on the same line is treated as a comment and is ignored by the JavaScript engine.\n     - Single-line comments are used for brief explanations or notes.\n\n     ```javascript\n     // This is a single-line comment\n     var x = 5; // Assigning a value to a variable\n\n     const area = 0.5 * base * height; // area of triangle = 1/2 * base * height\n\n     // TODO: Create a new Todo\n     console.log(\"Create a new Todo\");\n\n     // TODO: Read all the todos\n     // FIXME: Unable to read all the todos\n     console.log(\"Listed all the todos\");\n\n     // TODO: update a Todo\n     console.log(\"Todo is updated\");\n\n     // TODO: delete a todo\n     console.log(\"Todo is deleted\");\n     ```\n\n  2. **Multi-line Comments**:\n\n     - Enclosed between `/*` and `*/`.\n     - Multi-line comments can span across multiple lines and are often used for more extensive explanations, documentation, or temporarily \"commenting out\" blocks of code.\n\n     ```javascript\n     /*\n         This is a multi-line comment.\n         It can span across multiple lines.\n     */\n\n     /*\n     function oldCode() {\n         // This entire function is \"commented out\" and won't run.\n     }\n     */\n     ```\n\n  - **Needs and Use Cases for Comments in JavaScript**:\n\n  1. **Code Explanation**: Comments are used to explain complex sections of code, making it easier for developers (including yourself) to understand the purpose and functionality of code blocks.\n\n  2. **Documentation**: Comments can serve as a form of documentation, providing information on how to use functions, classes, or libraries, including descriptions of parameters and return values.\n\n  3. **TODO Lists**: Developers often use comments with \"TODO\" or \"FIXME\" labels to highlight areas of code that need attention or future enhancements.\n\n  4. **Disable Code**: Comments can be used to temporarily disable lines or blocks of code for debugging or testing purposes without deleting the code.\n\n  5. **Version History**: Comments can include information about the version of the code, date of last modification, and author details for version control and collaboration.\n\n  6. **Algorithmic Explanation**: When implementing complex algorithms, comments can help explain the logic and steps involved.\n\n  7. **Cross-browser Compatibility**: Comments may include notes about specific browser-related workarounds or compatibility issues.\n\n  8. **Debugging**: Comments can aid in debugging by providing context or identifying problematic areas.\n\n  9. **Code Organization**: Comments can be used to divide code into sections, making it easier to navigate and understand.\n\n  While comments are essential for code readability and collaboration, it's also crucial to keep them up to date. Outdated comments can be misleading and may not accurately reflect the current state of the code. Therefore, it's good practice to maintain comments as you make changes to your code.\n\n- **Tasks 1: Can you print your name, age, address?**\n- **Program 1: E-Commerce app [printing product details]**\n\n  ```js\n  // prodcut details\n  /*\n  id : 1\n  title : iphone 12\n  description: brilliant phone with 4k camera\n  price : 549\n  discountPercentage : 8\n  rating : 4.69\n  brand : Apple\n  */\n\n  // product actual price calculator [printing product details]\n  console.log(\"id : 1\");\n  console.log(\"title : iphone 12\");\n  console.log(\"description: brilliant phone with 4k camera\");\n  console.log(\"price : 510\");\n  console.log(\"discountPercentage : 8\");\n  console.log(\"rating : 4.69\");\n  console.log(\"brand : Apple\");\n  ```\n\n- setup prettier code formatter\n\n### 1.3 Tokens\n\n- Tokens are backbone of any programming language. Important tokens: keywords, puncuators, escape sequences, data type, variables, operators, etc.\n\n#### 1.3.1 Keywords, puncuators and Escape sequences\n\n- Keywords: javascript reserved words for specific reasons.\n\n  - Example - abstract, break, char, double, export, import, try, catch, finally, throw, throws, if, else, switch, case, break, default, continue,for, while, do, var, let, const, class, extends, implements, public, private, protected, new, static, this, true, false, boolean, string, number, function, instanceof\n\n- puncuators\n  - () round brackets / parentheses\n  - {} curly brackets / braces\n  - [] square brackets / brackets\n  - \u003c\u003e angle brackets / chevrons\n  - ; semicolon, : colon\n- Escape sequnces: \\ characters\n  Escape sequences in JavaScript are used to represent special characters or control characters within strings. They begin with a backslash (`\\`) followed by a specific character, and they are used to produce characters that are otherwise difficult to type or include in a string directly. Here are some common escape sequences in JavaScript:\n\n  1. **Newline (`\\n`)**: Represents a line break or a new line character.\n\n     ```javascript\n     var text = \"This is line 1.\\nThis is line 2.\";\n     console.log(text);\n     ```\n\n     Output:\n\n     ```js\n     This is line 1.\n     This is line 2.\n     ```\n\n  2. **Tab (`\\t`)**: Represents a tab character.\n\n     ```javascript\n     var indentedText = \"First\\tSecond\\tThird\";\n     console.log(indentedText);\n     ```\n\n     Output:\n\n     ```js\n     First   Second  Third\n     ```\n\n  3. **Backslash (`\\\\`)**: Represents a literal backslash character.\n\n     ```javascript\n     var filePath = \"C:\\\\Program Files\\\\MyApp\\\\file.txt\";\n     console.log(filePath);\n     ```\n\n     Output:\n\n     ```js\n     C:\\Program Files\\MyApp\\file.txt\n     ```\n\n  4. **Single Quote (`\\'`)**: Represents a single quotation mark within a single-quoted string.\n\n     ```javascript\n     var singleQuoted = \"This is an example of a single quote: 'Hello'\";\n     console.log(singleQuoted);\n     ```\n\n     Output:\n\n     ```js\n     This is an example of a single quote: 'Hello'\n     ```\n\n  5. **Double Quote (`\\\"`)**: Represents a double quotation mark within a double-quoted string.\n\n     ```javascript\n     var doubleQuoted = 'This is an example of a double quote: \"Hello\"';\n     console.log(doubleQuoted);\n     ```\n\n     Output:\n\n     ```js\n     This is an example of a double quote: \"Hello\"\n     ```\n\n  6. **Unicode Characters (`\\uXXXX`)**: Represents a character using its Unicode code point in hexadecimal (XXXX).\n\n     ```javascript\n     var smileyFace = \"\\u263A\";\n     console.log(smileyFace);\n     ```\n\n     Output:\n\n     ```js\n     ☺\n     ```\n\n  These escape sequences allow you to include special characters or characters that have special meanings within your strings without causing syntax errors or unexpected behavior.\n\n#### 1.3.2 Data types\n\nData types: [typeof operator] can help us to find out the data type of a value. Data types can be divided into 2: primitive \u0026 non-primitive/reference.\n\n- Primitive data types: Primitive data types are also known as in-built data types. String, Number, Bigint, boolean, null, undefined, symbol\n\n  - Example\n\n    ```js\n    // primitive data types -\u003e String, Number, Boolean, null, undefined, Symbol\n\n    // String data type -\u003e  Represents sequences of characters, such as text.\n    console.log(typeof \"John\"); // string\n    console.log(typeof \"\"); // empty string\n\n    // Boolean data type -\u003e Represents a true or false value.\n    console.log(typeof true); // boolean\n\n    // Number data type -\u003e Represents numeric values, both integers and floating-point numbers.\n    console.log(typeof 123); // number\n    console.log(typeof 123.5); // number\n\n    // Undefined: variable is declared but no value is assigned\n    // Undefined -\u003e data type for variable without value\n    console.log(typeof x); // undefined\n\n    // null -\u003e  Represents the intentional absence of any object or value.(fun: typeof null is object)\n    console.log(typeof null);\n\n    /*\n    Symbol is used as an identifier for object properties\n     Symbols are unique identifiers\n     introduced in ES6\n     it can be used when defining constants such as enum for uniqueness\n     */\n    const symbol1 = Symbol(\"foo\");\n    const symbol2 = Symbol(\"foo\");\n    console.log(typeof symbol1); // symbol\n    console.log(symbol1 === symbol2); // false\n\n    const symbol = Symbol(\"Bye\");\n    console.log(typeof symbol);\n    console.log(symbol);\n\n    // BigInt: Represents large integers with arbitrary precision (introduced in ECMAScript 2020). This data type can represent numbers greater than 253-1 which helps to perform operations on large numbers. The number is specified by writing ‘n’ at the end of the value\n\n    var bigNumber = 125522222222222222222222222222222222222n;\n    console.log(bigNumber);\n    ```\n\n- Non Primitive data types: non-primitive data types are derived from primitive data types. It is also known as derived data types or reference data types. Object (Array is also part of Object type), Function.\n\n  - Example\n\n    ```js\n    // Object type -\u003e Represents a collection of key-value pairs (properties) where values can be of any data type, including other objects.\n    console.log(tyoeof {name: 'anis'});\n    console.log(typeof [1,2,3]) // array is object type\n\n     // function type -\u003e Represents a reusable block of code that can be executed.\n     console.log( typeof function display () { }) // function type\n\n    ```\n\n- **what are the differences between primtive \u0026 non-primitive data types?**\n  ![primitive vs non-primitive](images/difference-between-primitive-and-non-primitive-datatypes-12-1650387712.png)\n\n  ```js\n  // Copying by value\n  let num1 = 5;\n  let num2 = num1; // num2 gets the value of num1\n\n  num2 = 10; // Modifying num2 does not affect num1\n\n  console.log(num1); // Output: 5\n  console.log(num2); // Output: 10\n\n  // Copying by reference\n  let arr1 = [1, 2, 3];\n  let arr2 = arr1; // arr2 references the same array as arr1\n\n  arr2.push(4); // Modifying arr2 also affects arr1\n\n  console.log(arr1); // Output: [1, 2, 3, 4]\n  console.log(arr2); // Output: [1, 2, 3, 4]\n  ```\n\n- **[truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) vs [Falsy value](https://developer.mozilla.org/en-US/docs/Glossary/Falsy)**\n  - falsy value: false, 0, 0.0, -0, -0.0, \"\",'',``,null, undefined, NAN (Not-a-Number)\n  - truthy value: all values except falsy value. {}, [], new Date(), Infinity etc.\n- **Data type conversion in js**\n  JavaScript provides several methods for type conversion, allowing you to convert data from one type to another. Here are some common methods and examples:\n\n  1. **Implicit Type Conversion (Coercion):** JavaScript automatically converts data types in certain situations. For example, when you use the `+` operator with different data types, JavaScript may implicitly convert them to a common type (usually a string or a number).\n\n     ```javascript\n     const num = 5;\n     const str = \"10\";\n\n     // JavaScript implicitly converts 'str' to a number before addition\n     const result = num + str; // result is 15 (a number)\n     ```\n\n  2. **Explicit Type Conversion (Type Casting):** You can explicitly convert data types using various methods. Here are some common ones:\n\n     - **String Conversion:** Use `String()` or `.toString()` to convert a value to a string.\n\n       ```javascript\n       const num = 42;\n       const str = String(num); // str is \"42\"\n       ```\n\n     - **Number Conversion:** Use `Number()`, `parseInt()`, or `parseFloat()` to convert a value to a number.\n\n       ```javascript\n       const str = \"3.14\";\n       const num = Number(str); // num is 3.14\n\n       const intStr = \"42\";\n       const intNum = parseInt(intStr); // intNum is 42\n       ```\n\n     - **Boolean Conversion:** Use `Boolean()` to convert a value to a boolean.\n\n       ```javascript\n       const value = \"Hello\";\n       const bool = Boolean(value); // bool is true (non-empty strings are truthy)\n       ```\n\n  3. **Explicit Type Conversion to Arrays and Objects:** You can convert values to arrays or objects using specific constructors or methods.\n\n     - **Array Conversion:** Use `Array.from()` to convert iterable objects (like strings or arrays-like objects) into arrays.\n\n       ```javascript\n       const str = \"hello\";\n       const arr = Array.from(str); // arr is ['h', 'e', 'l', 'l', 'o']\n       ```\n\n     - **Object Conversion:** You can create objects using object literal syntax `{}`.\n\n       ```javascript\n       const keyValuePairs = [\n         [\"a\", 1],\n         [\"b\", 2],\n       ];\n       const obj = Object.fromEntries(keyValuePairs); // obj is { a: 1, b: 2 }\n       ```\n\n#### 1.3.3 Variables\n\n- Varibale is a placeholder for storing data.\n\n  ```js\n  let title = \"iphone 12\";\n  let price = 510;\n  let discountPercentage = 8.5;\n  ```\n\n- variables naming rules (collected from w3school)\n\n  - The general rules for constructing names for variables (unique identifiers) are:\n  - Names can contain letters, digits, underscores, and dollar signs.\n  - Names must begin with a letter\n  - Names can also begin with $ and \\_ (but we will not use it in this tutorial)\n  - Names are case sensitive (y and Y are different variables)\n  - Reserved words (like JavaScript keywords) cannot be used as names\n\n- Naming Convention: 4 most popular variable naming style out of many formats [naming conventions](\u003chttps://en.wikipedia.org/wiki/Naming_convention_(programming)\u003e)\n\n  - Underscore: first_name, last_name\n  - Upper Camel Case (Pascal Case): FirstName, LastName -\u003e normally used for Classes (nouns)\n  - Lower Camel Case: firstName, lastName -\u003e normally used for methods/variables\n  - SCREAMING SNAKE CASE / CONSTANT_CASE for naming constants\n  - Program 2: E-Commerce app [printing product details dynamically]\n\n    ```js\n    // Program 2: printing product details dynamically\n    const id = 101;\n    const title = \"iphone 12\";\n    const description = \"brilliant phone with 4k camera\";\n    const price = 549;\n    const discountPercentage = 8;\n    const rating = 4.69;\n    const brand = \"Apple\";\n\n    console.log(\"id : \" + id);\n    console.log(\"title : \" + title);\n    console.log(\"description: \" + description);\n    console.log(\"price : \" + price);\n    console.log(\"discountPercentage : \" + discountPercentage);\n    console.log(\"rating : \" + rating);\n    console.log(\"brand : \" + brand);\n    ```\n\n#### 1.3.4 Operators \u0026 string concatenation\n\nOperators: Symbol that helps us to do mathmatical operation. 3 major types: Unary (works with one operand), binary (works with 2 operands), ternary (3 operands).\n\n- Types of operators\n\n  - Arithmetic operators : +, -, \\*, /, %\n\n  - **Program 3: E-Commerce app [operators]**\n\n    ```js\n    // Program 3: E-Commerce app [operators]\n    const id = 101;\n    const title = \"iphone 12\";\n    const description = \"brilliant phone with 4k camera\";\n    const price = 549;\n    const discountPercentage = 8.5;\n    const rating = 4.69;\n    const brand = \"Apple\";\n\n    // calculating price after discount\n    const discountAmount = (price * discountPercentage) / 100;\n    const priceAfterDiscount = price - discountAmount;\n\n    console.log(\"id : \" + id);\n    console.log(\"title : \" + title);\n    console.log(\"description: \" + description);\n    console.log(\"price : \" + price + \" euros\");\n    console.log(\"discountPercentage : \" + discountPercentage);\n    console.log(\"rating : \" + rating);\n    console.log(\"brand : \" + brand);\n    console.log(\"priceAfterDiscount : \" + priceAfterDiscount + \" euros\");\n    ```\n\n  - **Arithmetic Programs: Create normal calculator, algebra formula calculator, area calculator (triangle,circle), temperature calculator(fahrenheit-celsius), years to hours, swap 2 numbers.**\n\n  - Assignment operators: +=, -=, \\*=, /=, %=\n\n  - Comparision / Relational operators: \u003e, \u003e=, \u003c, \u003c=, ==, !=, ===, !== .Result is always boolean value\n\n    ```js\n    let num1 = 20;\n    let num2 = 10;\n\n    console.log(num1 \u003e num2); // true\n    console.log(num1 \u003e= num2); // true\n    console.log(num1 \u003c num2); // false\n    console.log(num1 \u003c= num2); // false\n    console.log(num1 === num2); // false\n    console.log(num1 !== num2); // true\n    ```\n\n  - Logical operators: \u0026\u0026, ||, ! result is always boolean value\n\n    ```js\n    let num1 = 20;\n    let num2 = 10;\n    let num3 = 5;\n\n    console.log(num1 \u003e num2 \u0026\u0026 num1 \u003e num3); // true\n    console.log(num2 \u003e num1 \u0026\u0026 num2 \u003e num3); // false\n    console.log(num3 \u003e num1 \u0026\u0026 num3 \u003e num2); // false\n    console.log(num3 \u003e num1 || num3 \u003e num2); // false\n    console.log(num2 \u003e num1 || num2 \u003e num3); // true\n    ```\n\n  - Bitwise operators: \u0026, |, ^, ~, \u003e\u003e, \u003c\u003c\n\n  - Unary operators: + (unary plus), -(unary minus), ++ (increment), -- (decrement)\n\n  - Ternary/conditional Operator: `condition ? expression1 : expression2;`\n\n- Prompt \u0026 Data Type conversion: prompt() can help us to take user input. Though it is not recommended but for testing purpose we can use it instead of a form. Number(), toString(), pasreInt(), parseFloat(), parseDouble()\n\n  - **Program 4: E-Commerce app [adding prompt(), \u0026 Number function]**\n\n    ```js\n    // Program 4: E-Commerce app [adding prompt(), \u0026 Number function]\n    const id = 101;\n    const title = \"iphone 12\";\n    const description = \"brilliant phone with 4k camera\";\n    const price = 549;\n    const rating = 4.69;\n    const brand = \"Apple\";\n\n    // getting user input using prompt()\n    const discountPercentage = Number(prompt(\"Discount percentage? \"));\n\n    // calculating price after discount\n    const discount = (price * discountPercentage) / 100;\n    const priceAfterDiscount = price - discount;\n\n    console.log(\"id : \" + id);\n    console.log(\"title : \" + title);\n    console.log(\"description: \" + description);\n    console.log(\"price : \" + price + \" euros\");\n    console.log(\"discountPercentage : \" + discountPercentage);\n    console.log(\"rating : \" + rating);\n    console.log(\"brand : \" + brand);\n    console.log(\"priceAfterDiscount : \" + priceAfterDiscount + \" euros\");\n    ```\n\n### 1.4 Control statement\n\n#### 1.4.1 Conditional control statement: if, else if, else, switch\n\n- **if, else if, else**\n\n  ```js\n  // if syntax\n  // if the condition is true then if body will work\n  if (condition) {\n    // the body of if\n  }\n\n  // if, else syntax\n  // if the condition is true then if body will work or else will work\n  if (condition) {\n    // the body of if\n  } else {\n    // the body of else\n  }\n\n  // if, else if, else syntax\n  if (condition) {\n    // the body of if\n  } else if (condition) {\n    // the body of else if\n  } else if (condition) {\n    // the body of else if\n  } else {\n    // the body of else\n  }\n  ```\n\n- if, else if, else related programs\n\n  - positive / negative / zero program\n  - Even / odd program\n  - Vowel / consonant program\n  - find large / small number program\n  - digit spelling program\n  - [leap year program](https://www.tutorialspoint.com/learn_c_by_examples/leap_year_program_in_c.htm)\n\n    ```js\n    // a program that will find a large number between 2 numbers\n    var num1 = parseInt(prompt(\"Enter first numebr : \"));\n    var num2 = parseInt(prompt(\"Enter second numebr : \"));\n\n    // first method - using only if\n    if (num1 \u003e num2) {\n      console.log(\"Large Number is : \" + num1);\n    }\n    if (num1 \u003c num2) {\n      console.log(\"Large Number is : \" + num2);\n    }\n    if (num1 == num2) {\n      console.log(\"Equal numbers\");\n    }\n\n    // second method - more efficient than first method\n    if (num1 \u003e num2) {\n      console.log(\"Large Number is : \" + num1);\n    } else if (num1 \u003c num2) {\n      console.log(\"Large Number is : \" + num2);\n    } else if (num1 == num2) {\n      console.log(\"Equal numbers\");\n    }\n\n    // third method - more efficient than first and second method\n    if (num1 \u003e num2) {\n      console.log(\"Large Number is : \" + num1);\n    } else if (num1 \u003c num2) {\n      console.log(\"Large Number is : \" + num2);\n    } else {\n      console.log(\"Equal numbers\");\n    }\n\n    // A program that will find a letter is vowel or consonant\n    var letter = prompt(\"Enter a letter : \");\n\n    // convert any uppercase input into lower cause we set only lowercase letter in condition\n    letter = letter.toLowerCase();\n\n    // Now check the condition\n    if (\n      letter == \"a\" ||\n      letter == \"e\" ||\n      letter == \"i\" ||\n      letter == \"o\" ||\n      letter == \"u\"\n    ) {\n      console.log(\"Vowel\");\n    } else {\n      console.log(\"Consonant\");\n    }\n    ```\n\n- **Program 5 : E-commerce app [conditional control statement if/else]**\n\n  ```js\n  const id = 101;\n  const title = \"iphone 12\";\n  const description = \"brilliant phone with 4k camera\";\n  const price = 549;\n  const rating = 4.69;\n  const brand = \"Apple\";\n  let priceAfterDiscount;\n\n  // getting user input using prompt()\n  const discountPercentage = Number(prompt(\"Discount percentage? \"));\n\n  if (discountPercentage \u003c 0) {\n    console.log(\"Not a valid discount percentage\");\n  } else {\n    // calculating price after discount\n    const discountAmount = (price * discountPercentage) / 100;\n    priceAfterDiscount = price - discountAmount;\n  }\n\n  console.log(\"id : \" + id);\n  console.log(\"title : \" + title);\n  console.log(\"description: \" + description);\n  console.log(\"price : \" + price + \" euros\");\n  console.log(\"discountPercentage : \" + discountPercentage);\n  console.log(\"rating : \" + rating);\n  console.log(\"brand : \" + brand);\n  console.log(\"priceAfterDiscount : \" + priceAfterDiscount + \" euros\");\n  ```\n\n- **switch**: An alternative for if, else. 4 keywords: switch, case, break, default\n\n  ```js\n  // A program to understand switch -\u003e digit spelling program\n  // 0 -\u003e Zero\n  // 1 -\u003e One\n  // 2 -\u003e Two\n  // ...\n  // ...\n  // 9 -\u003e Nine\n  // for any number program will display \"not a digit\"\n\n  var digit = parseInt(prompt(\"Enter a digit : \"));\n  switch (digit) {\n    case 0:\n      console.log(\"Zero\");\n      break;\n\n    case 1:\n      console.log(\"One\");\n      break;\n\n    case 2:\n      console.log(\"Two\");\n      break;\n\n    case 3:\n      console.log(\"Three\");\n      break;\n\n    case 4:\n      console.log(\"Four\");\n      break;\n\n    case 5:\n      console.log(\"Five\");\n      break;\n\n    case 6:\n      console.log(\"Six\");\n      break;\n\n    case 7:\n      console.log(\"Seven\");\n      break;\n\n    case 8:\n      console.log(\"Eight\");\n      break;\n\n    case 9:\n      console.log(\"Nine\");\n      break;\n\n    default:\n      console.log(\"Not a digit\");\n  }\n  ```\n\n#### 1.4.2 Loop control statement\n\n- for loop\n\n  ```js\n  //A program to demonstrate for loop\n  for (var i = 1; i \u003c= 10; i++) {\n    console.log(\"Bangladesh\");\n  }\n\n  console.log(\"End of for loop\");\n\n  // sum of numbers 1+2+..+100\n  // var sum = 0;\n  // for (var x = 1; x \u003c= 100; x++){\n  //     sum = sum + x;\n  // }\n  // console.log(sum);\n  ```\n\n- while loop\n\n  ```js\n  //A program to demonstrate while loop\n  var i = 1;\n  while (i \u003c= 10) {\n    console.log(\"Bangladesh\");\n    i++;\n  }\n\n  console.log(\"End of for loop\");\n\n  // sum of numbers 1+2+..+100\n  // var sum = 0;\n  // var x = 1;\n  // while ( x \u003c= 100){\n  //     sum = sum + x;\n  //     x++;\n  // }\n  // console.log(sum);\n  ```\n\n- do while loop\n\n  ```js\n  // A program to demonstrate do while loop\n  var i = 1;\n  do {\n    console.log(\"Bangladesh\");\n    i++;\n  } while (i \u003c= 10);\n\n  console.log(\"End of for loop\");\n\n  // sum of numbers 1+2+..+100\n  // var sum = 0;\n  // var x = 1;\n  // do{\n  //     sum = sum + x;\n  //     x++;\n  // }while ( x \u003c= 100)\n  // console.log(sum);\n  ```\n\n- for of loop: The for...of loop is used for iterating over the values of iterable objects like arrays and strings.\n\n  ```js\n  const colors = [\"red\", \"green\", \"blue\"];\n\n  for (const color of colors) {\n    console.log(color);\n  }\n\n  // Output:\n  // \"red\"\n  // \"green\"\n  // \"blue\"\n  ```\n\n- for in loop: The for...in loop is used for iterating over the keys (property names) of objects. It should not be used to iterate over arrays because it may also iterate over object prototype properties.\n\n  ```js\n  const person = {\n    name: \"John\",\n    age: 30,\n    job: \"Engineer\",\n  };\n\n  for (const key in person) {\n    console.log(key + \": \" + person[key]);\n  }\n\n  // Output:\n  // \"name: John\"\n  // \"age: 30\"\n  // \"job: Engineer\"\n  ```\n\n#### 1.4.3 jump control statement\n\n- break and continue statement\n\n  ```js\n  // break and continue keyword program\n\n  // The break statement \"jumps out\" of a loop or switch if the condition is matched.\n  for (var i = 1; i \u003c= 100; i++) {\n    if (i == 20) break;\n    console.log(i);\n  }\n\n  // The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.\n  for (var i = 1; i \u003c= 100; i++) {\n    if (i == 20) continue;\n    console.log(i);\n  }\n  ```\n\n### 1.5 Function - traditional\n\n- Function: Function is a block of codes for a specific task. It is beneficial for reusablity. Separation of concerns. **return keyword can be used only once inside a function.** **value that a function received is called parameters and the value we pass when calling function is known as arguments**\n- Function related topics:\n\n  - How to define a function?\n  - How to call a function?\n  - How to pass parameters to a function?\n  - How to return a value from a function?\n\n  ```js\n  // function example 2\n  // without function\n  let num1; // best practice: always slipt the declaration as I did in 3 lines\n  let num2;\n  let sum;\n\n  num1 = 20;\n  num2 = 30;\n  sum = num1 + num2;\n  console.log(sum);\n\n  num1 = 10;\n  num2 = 20;\n  sum = num1 + num2;\n  console.log(sum);\n\n  num1 = 40;\n  num2 = 20;\n  sum = num1 + num2;\n  console.log(sum);\n\n  // with function\n  function addNumbers(num1, num2) {\n    const sum = num1 + num2;\n    console.log(sum);\n  }\n\n  addNumbers(20, 30);\n  addNumbers(10, 30);\n  addNumbers(5, 15);\n  ```\n\n  ```js\n  // Function example3\n\n  // creating function without parameter\n  function message() {\n    console.log(\"Hello, I am a function without parameter\");\n  }\n\n  // creating function with one parameter\n  function welcomeMessage(name) {\n    console.log(\"Welcome \" + name + \"to the Full-stack\");\n  }\n\n  // creating function with multiple parameters\n  function welcomeMessage2(name, programName) {\n    console.log(\"Welcome \" + name + \"to the \" + programName);\n  }\n\n  // returning from a function\n  function welcomeMessage3(name, programName) {\n    return \"Welcome \" + name + \"to the \" + programName;\n  }\n\n  // calling functions\n  message();\n  welcomeMessage(\"Alex\");\n  welcomeMessage2(\"Alex\", \"full-stack\");\n  console.log(welcomeMessage3(\"Brown\", \"full-stack\"));\n  ```\n\n- **Program 6: E-Commerce app [function]**\n\n  ```js\n  // Program 6: E-commerce app  [function]\n\n  const id = 101;\n  const title = \"iphone 12\";\n  const description = \"brilliant phone with 4k camera\";\n  const price = 549;\n  const rating = 4.69;\n  const brand = \"Apple\";\n\n  // getting user input using prompt()\n  const discountPercentage = Number(prompt(\"Discount percentage? \"));\n\n  // priceAfterDiscount function\n  function priceAfterDiscount(price, discountPercentage) {\n    if (discountPercentage \u003c 0) {\n      console.log(\"Not a valid discount percentage\");\n      return 0;\n    } else {\n      // calculating price after discount\n      const discountAmount = (price * discountPercentage) / 100;\n      return price - discountAmount;\n    }\n  }\n\n  // printing product details\n  function printProductDetails(\n    pId,\n    pTitle,\n    pDescription,\n    pPrice,\n    pRating,\n    pBrand,\n    pDiscountPercentage\n  ) {\n    console.log(\"id : \" + pId);\n    console.log(\"title : \" + pTitle);\n    console.log(\"description : \" + pDescription);\n    console.log(\"rating : \" + pRating);\n    console.log(\"brand : \" + pBrand);\n    console.log(\"Original price : \" + pPrice + \" euros\");\n    console.log(\"Discount Percentage : \" + pDiscountPercentage);\n    console.log(\n      \"After the discount price : \" +\n        priceAfterDiscount(price, pDiscountPercentage) +\n        \" euros\"\n    );\n  }\n\n  printProductDetails(\n    id,\n    title,\n    description,\n    price,\n    rating,\n    brand,\n    discountPercentage\n  );\n  ```\n\n#### Function related Programs\n\n- create a simple function for calculating square\n- create a simple function for calculating double, triple\n- create functions for addition, subtraction\n- create a function for checking a number is even or odd\n- create a function for checking largest number between 2/3 numbers\n- put all if-else related programs inside functions\n\n### 1.6 Hoisting, Scope of Variables , closures\n\n#### 1.6.1 Hoisting\n\nHoisting is a JavaScript behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase. This means that you can use variables and functions in code before they are declared in the source code. However, there is a distinction between variable and function hoisting.\n\n1. **Variable Hoisting**:\n\n   Variables declared with `var` are hoisted. This means that they are moved to the top of their function or global scope, and their initial value is set to `undefined`.\n\n   ```javascript\n   console.log(x); // undefined\n   var x = 5;\n   ```\n\n   In the above example, `x` is hoisted, but its value is `undefined` until it's assigned the value `5`.\n\n2. **Function Hoisting**:\n\n   Function declarations are also hoisted. You can call a function before its declaration in the code.\n\n   ```javascript\n   sayHello(); // Hello, world!\n\n   function sayHello() {\n     console.log(\"Hello, world!\");\n   }\n   ```\n\n   In this case, the function `sayHello` is hoisted to the top of the scope, so you can call it before its actual declaration in the code.\n\n3. **Block-Scoped Variables (let and const)**:\n\n   Variables declared with `let` and `const` are also hoisted, but they are not initialized with `undefined`. Instead, they are in a \"temporal dead zone\" until they are declared in the code.\n\n   ```javascript\n   console.log(x); // ReferenceError: x is not defined\n   let x = 5;\n   ```\n\n   Unlike `var`, if you try to access a `let` or `const` variable before its declaration, it will result in a `ReferenceError`.\n\nIt's important to understand hoisting because it can lead to unexpected behavior in your code if you're not aware of how it works. To avoid issues, it's generally a good practice to declare variables at the beginning of their containing scope and to use `let` and `const` for better scoping behavior compared to `var`.\n\n#### 1.6.2 scope and closures\n\nIn JavaScript, the scope of a variable refers to the context in which the variable is declared and can be accessed. The scope determines where in your code a variable is visible and can be used. JavaScript has two main types of variable scope: **global scope** and **local scope** (also known as function scope). Understanding variable scope is crucial for writing clean, maintainable, and bug-free JavaScript code. It helps prevent unintended variable name collisions and allows you to control the visibility and lifetime of variables in your programs.\n\n1. **Global Scope:**\n\n   - Variables declared outside of any function, including at the top level of a JavaScript file, have global scope.\n   - Global variables are accessible from anywhere in your code, both within functions and outside functions.\n   - Be cautious with global variables, as they can lead to naming conflicts and make it harder to maintain your code.\n\n   ```javascript\n   var globalVar = \"I'm global\"; // Global scope\n   function foo() {\n     console.log(globalVar); // Accessible within functions\n   }\n   console.log(globalVar); // Accessible outside functions\n   ```\n\n2. **Local Scope (Function Scope):**\n\n   - Variables declared inside a function have local scope.\n   - Local variables are only accessible within the function where they are declared. They are not visible outside of the function.\n   - Each function creates its own scope, and nested functions have access to variables in their parent functions.\n\n   ```javascript\n   function bar() {\n     var localVar = \"I'm local\"; // Local scope\n     console.log(localVar); // Accessible within the function\n   }\n   bar();\n   console.log(localVar); // Error: localVar is not defined\n   ```\n\n3. **Block Scope (ES6 and Later):**\n\n   - With the introduction of ECMAScript 6 (ES6), the `let` and `const` keywords allow for block-scoped variables.\n   - Block scope refers to variables declared within blocks, such as `if` statements or `for` loops. These variables are only accessible within the block where they are declared.\n\n   ```javascript\n   if (true) {\n     let blockVar = \"I'm block-scoped\"; // Block scope\n     console.log(blockVar); // Accessible within the block\n   }\n   console.log(blockVar); // Error: blockVar is not defined\n   ```\n\n4. **Lexical Scope (Closures):**\n\n   - Lexical scope refers to the way JavaScript determines the scope of variables at the time of function creation.\n   - Closures occur when a function is defined within another function and retains access to its parent function's variables, even after the parent function has finished executing.\n\n   ```javascript\n   function outer() {\n     var outerVar = \"I'm in outer scope\";\n     function inner() {\n       console.log(outerVar); // Accesses outerVar via closure\n     }\n     return inner;\n   }\n   var closureFunc = outer();\n   closureFunc(); // Logs \"I'm in outer scope\"\n   ```\n\n- More on clousre\n  Certainly, here's an example of a closure in JavaScript:\n\n  ```javascript\n  function outer() {\n    var outerVar = \"I'm in the outer function\"; // Outer variable\n\n    function inner() {\n      console.log(outerVar); // Accesses outerVar from the outer function\n    }\n\n    return inner; // Return the inner function\n  }\n\n  // Create a closure by calling outer and assigning its result to a variable\n  var closureFunc = outer();\n\n  // Execute the closure\n  closureFunc(); // Logs \"I'm in the outer function\"\n  ```\n\n  In this example:\n\n  1. We have an outer function called `outer` that defines a variable `outerVar` within its scope.\n\n  2. Inside the `outer` function, there's an inner function called `inner`.\n\n  3. The `inner` function has access to the `outerVar` variable even though it's declared in the outer function. This is an example of a closure. Closures allow inner functions to \"remember\" the scope in which they were created, even after the outer function has finished executing.\n\n  4. We return the `inner` function from the `outer` function, creating a closure.\n\n  5. We assign the returned `inner` function to the variable `closureFunc`.\n\n  6. When we execute `closureFunc()`, it logs the value of `outerVar`, which is still accessible due to the closure.\n\n  Closures are powerful because they allow you to encapsulate data and behavior, creating private variables and functions that can be used to manage state or implement various patterns like the module pattern and the revealing module pattern in JavaScript.\n\n#### 1.6.3 Var, let, const\n\n- 2 important things: reassign, scope - block, function, global.\n\n- var variable can be reassigned and function scoped. var variables also become part of window object which can be overriden. try window.varName\n\n  ```js\n  var name = \"alex\";\n  name = \"robin\"; // reassign allowed for var variables\n\n  if (true) {\n    var age = 32;\n  }\n\n  console.log(name);\n  console.log(age); // allowed as var variable is function scoped\n  ```\n\n- let variable can be reassigned but blocked (a set of curly braces) scoped.\n\n  ```js\n  let name = \"alex\";\n  name = \"robin\"; // reassign allowed for let variables\n\n  if (true) {\n    let age = 32;\n  }\n\n  console.log(name);\n  console.log(age); // not allowed as let variable is block scoped\n  ```\n\n- const variable can not be reassigned but blocked (a set of curly braces) scoped. const object can be changed by its properties.\n\n  ```js\n  const name = \"alex\";\n  name = \"robin\"; // reassign is not allowed for const variables\n\n  if (true) {\n    const age = 32;\n  }\n\n  console.log(name);\n  console.log(age); // not allowed as const variable is blocked scoped\n  ```\n\n### 1.7 Objects\n\nObject: In JavaScript, objects are fundamental data structures used to store and organize data. Objects are collections of key-value pairs, where each key is a string (or a symbol in ES6+) that acts as a unique identifier for a value. Values in objects can be of any data type, including other objects, functions, arrays, and primitive types (like strings, numbers, and booleans).\n\n- object examples are given below\n\n```js\n// Creating an empty object\nconst person = {};\n\n// Adding properties to the object\nperson.firstName = \"John\";\nperson.lastName = \"Doe\";\nperson.age = 30;\n\n// Accessing object properties\nconsole.log(person.firstName); // \"John\"\nconsole.log(person.lastName); // \"Doe\"\nconsole.log(person.age); // 30\n\n// Objects can also be created with properties in a single step\nconst car = {\n  make: \"Toyota\",\n  model: \"Camry\",\n  year: 2022,\n};\n\n// Accessing properties using square brackets (useful when the property name is dynamic)\nconst propertyName = \"make\";\nconsole.log(car[propertyName]); // \"Toyota\"\n\n// Nested objects\nconst student = {\n  name: \"Alice\",\n  info: {\n    major: \"Computer Science\",\n    GPA: 3.9,\n  },\n};\n\nconsole.log(student.info.major); // \"Computer Science\"\nconsole.log(student[\"info\"][\"GPA\"]); // 3.9\n\n// Deleting a property\ndelete car.year;\n\n// Checking if a property exists\nconsole.log(\"make\" in car); // true\nconsole.log(\"year\" in car); // false\n\n// Iterating through object properties\nfor (const key in car) {\n  console.log(key, car[key]);\n}\n\n// Object methods (functions attached to objects)\nconst calculator = {\n  add: function (a, b) {\n    return a + b;\n  },\n  subtract: function (a, b) {\n    return a - b;\n  },\n};\n\nconsole.log(calculator.add(5, 3)); // 8\nconsole.log(calculator.subtract(10, 4)); // 6\n```\n\n```js\nconst student = {\n  name: \"Anisul Islam\", // property\n  displayInfo: function () {\n    // method related to object\n    return `Hello! My name is ${this.name}`;\n  },\n};\n\nconsole.log(student.name);\nconsole.log(student.displayInfo());\n```\n\n```js\n// object program example\n// what is Object?\n// How to create an object?\n// How to access object properties?\n// Constructor, this keyword\n// function inside constructor\n\n// declaring variables and using them\nconst name = \"Anisul Islam\";\nconst age = 27;\nconst cgpa = 3.92;\nconst lang = [\"Bengali\", \"English\"];\n\n// declaring objects -\u003e object is one type of variable that can store differnt types of variables\nconst student1 = {\n  // property : value\n  name: \"Anisul Islam\",\n  age: 27,\n  cgpa: 3.92,\n  lang: [\"Bengali\", \"English\"],\n};\n\nconst student2 = {\n  // property : value\n  name: \"Rokib\",\n  age: 28,\n  cgpa: 2.92,\n  lang: [\"Hindi\", \"Bengali\"],\n};\n\nconst student3 = {\n  // property : value\n  name: \"Sweety\",\n  age: 25,\n  cgpa: 4.92,\n  lang: [\"Bengali\", \"Urdu\"],\n};\n// printing object property's value\n// object properties can be accessed in two ways: objectName.propertyName or objectName[\"propertyName\"]\nconsole.log(student1.name);\nconsole.log(student1[name]);\nconsole.log(student1);\n\nconsole.log(\"using constructor\");\n// adding constructor and simplifying the task\n\nfunction Student(name, age, cgpa, lang) {\n  this.name = name;\n  this.age = age;\n  this.cgpa = cgpa;\n  this.lang = lang;\n\n  // adding function inside the constructor\n  /*\n  object properties that holds a function is called Method. Use dot operator for accessing. we can declare the function outside then use here\n  */\n  this.display = function () {\n    console.log(this.name);\n  };\n  \u003c!-- this.display = function d() {\n    console.log(this.name);\n  }; --\u003e\n\n  this.display = d;\n}\n\n  function d() {\n    console.log(this.name);\n  };\n\nconst s1 = new Student(\"Anisul Islam\", 27, 3.92, [\"Bengali\", \"English\"]);\nconst s2 = new Student(\"Rabeya Begum\", 23, 4.92, [\"Bengali\", \"Urdu\"]);\nconst s3 = new Student(\"Milon\", 29, 4.68, [\"Bengali\", \"Hindi\"]);\n\nconsole.log(s1);\nconsole.log(s2);\nconsole.log(s3);\ns1.display();\n```\n\n```js\n// contact manager app\nfunction contact(name, number) {\n  this.name = name;\n  this.number = number;\n\n  this.print = function () {\n    console.log(`${this.name}: ${this.number}`);\n  };\n}\n\nconst a = new contact(\"David\", 12345);\nconst b = new contact(\"Amy\", 987654321);\na.print();\nb.print();\n```\n\n- an example of methods\n\n```js\nconst Calculator = {\n  add: function (num1, num2) {\n    return num1 + num2;\n  },\n  sub: function (num1, num2) {\n    return num1 - num2;\n  },\n};\n\nconsole.log(Calculator.add(20, 30));\nconsole.log(Calculator.sub(20, 30));\n```\n\n- **Program 7 : E-commerce app [object]**\n\n  ```js\n  // Program 7: E-commerce app [object]\n\n  const product = {\n    id: 101,\n    title: \"iphone 12\",\n    description: \"brilliant phone with 4k camera\",\n    price: 549,\n    discountPercentage: 8.5,\n    rating: 4.69,\n    brand: \"Apple\",\n    insuranceCost: 8,\n  };\n\n  // getting user input using prompt()\n  const discountPercentage = Number(prompt(\"Discount percentage? \"));\n\n  // priceAfterDiscount function\n  function priceAfterDiscount(price, discountPercentage) {\n    if (discountPercentage \u003c 0) {\n      console.log(\"Not a valid discount percentage\");\n      return 0;\n    } else {\n      // calculating price after discount\n      const discount = (price * discountPercentage) / 100;\n      return price - discount;\n    }\n  }\n\n  // printing product details\n  function printProductDetails(\n    pId,\n    pTitle,\n    pDescription,\n    pPrice,\n    pRating,\n    pBrand,\n    pDiscountPercentage\n  ) {\n    console.log(\"id : \" + pId);\n    console.log(\"title : \" + pTitle);\n    console.log(\"description : \" + pDescription);\n    console.log(\"rating : \" + pRating);\n    console.log(\"brand : \" + pBrand);\n    console.log(\"Original price : \" + pPrice + \" euros\");\n    console.log(\"Discount Percentage : \" + pDiscountPercentage);\n    console.log(\n      \"After the discount price : \" +\n        priceAfterDiscount(pPrice, pDiscountPercentage) +\n        \" euros\"\n    );\n  }\n\n  printProductDetails(\n    product.id,\n    product.title,\n    product.description,\n    product.price,\n    product.rating,\n    product.brand,\n    discountPercentage\n  );\n  ```\n\n- **Program 8 : E-commerce app [More object]**\n\n  ```js\n  // Program 8: E-commerce app [More on object]\n\n  const product1 = {\n    id: 101,\n    title: \"iphone 12\",\n    description: \"brilliant phone with 4k camera\",\n    price: 549,\n    discountPercentage: 8.5,\n    rating: 4.69,\n    brand: \"Apple\",\n    insuranceCost: 8,\n  };\n  const product2 = {\n    id: 102,\n    title: \"iphone 13\",\n    description: \"brilliant phone with 4k camera\",\n    price: 649,\n    discountPercentage: 7.5,\n    rating: 4.5,\n    brand: \"Apple\",\n    insuranceCost: 12,\n  };\n  const product3 = {\n    id: 103,\n    title: \"samsung s10\",\n    description: \"brilliant phone with 2k camera\",\n    price: 349,\n    discountPercentage: 12.5,\n    rating: 3.5,\n    brand: \"Samsung\",\n    insuranceCost: 5,\n  };\n\n  // getting user input using prompt()\n  const discountPercentage = Number(prompt(\"Discount percentage? \"));\n\n  // priceAfterDiscount function\n  function priceAfterDiscount(price, discountPercentage) {\n    if (discountPercentage \u003c 0) {\n      console.log(\"Not a valid discount percentage\");\n      return 0;\n    } else {\n      // calculating price after discount\n      const discount = (price * discountPercentage) / 100;\n      return price - discount;\n    }\n  }\n\n  // printing product details\n  function printProductDetails(\n    pId,\n    pTitle,\n    pDescription,\n    pPrice,\n    pRating,\n    pBrand,\n    pDiscountPercentage\n  ) {\n    console.log(\"id : \" + pId);\n    console.log(\"title : \" + pTitle);\n    console.log(\"description : \" + pDescription);\n    console.log(\"rating : \" + pRating);\n    console.log(\"brand : \" + pBrand);\n    console.log(\"Original price : \" + pPrice + \" euros\");\n    console.log(\"Discount Percentage : \" + pDiscountPercentage);\n    console.log(\n      \"After the discount price : \" +\n        priceAfterDiscount(pPrice, pDiscountPercentage) +\n        \" euros\"\n    );\n  }\n\n  printProductDetails(\n    product1.id,\n    product1.title,\n    product1.description,\n    product1.price,\n    product1.rating,\n    product1.brand,\n    product1.discountPercentage\n  );\n\n  printProductDetails(\n    product2.id,\n    product2.title,\n    product2.description,\n    product2.price,\n    product2.rating,\n    product2.brand,\n    product2.discountPercentage\n  );\n\n  printProductDetails(\n    product3.id,\n    product3.title,\n    product3.description,\n    product3.price,\n    product3.rating,\n    product3.brand,\n    product3.discountPercentage\n  );\n  ```\n\n### 1.8 Arrays\n\n- Array is a collection of similar data type mostly.\n- Array VS Object -\u003e arrays use numbered indexes. but, objects use named indexes.\n\n- Array syntax \u0026 example\n\n  ```js\n  // Array example 1\n  // creating an array with 20 variables\n  var names = new Array(20);\n\n  //array index always start with 0\n  names[0] = \"Anisul\";\n  names[1] = \"Sonali\";\n\n  //printing an array elements\n  console.log(names[1]);\n\n  // creating an array with values\n  var students = [\"Anisul\", \"Sonali\", \"Priya\", \"Numan\"];\n  console.log(\"students = \" + students);\n  console.log(\"studnet at 2 index : \" + students[2]);\n\n  //finding the length of an array\n  console.log(\"Length of student array : \" + students.length);\n\n  // 2d array\n  let matrix = [\n    [1, 2],\n    [3, 4],\n  ];\n\n  console.log(matrix[0][1]);\n  ```\n\n- Program 9: E-commerce app [Array \u0026 loop]\n\n  ```js\n  // data collected from API - https://dummyjson.com/products\n  // Program 9: E-commerce app [Array \u0026 loop]\n  const products = [\n    {\n      id: 101,\n      title: \"iphone 9\",\n      description: \"brilliant phone with 4k camera\",\n      price: 549,\n      discountPercentage: 8.5,\n      rating: 4.69,\n      brand: \"Apple\",\n      insuranceCost: 8,\n    },\n    {\n      id: 102,\n      title: \"iphone X\",\n      description:\n        \"SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...\",\n      price: 899,\n      discountPercentage: 17.94,\n      rating: 4.44,\n      brand: \"Apple\",\n      insuranceCost: 8,\n    },\n    {\n      id: 103,\n      title: \"Samsung Universe 9\",\n      description:\n        \"Samsung's new variant which goes beyond Galaxy to the Universe\",\n      price: 1249,\n      discountPercentage: 15.46,\n      rating: 4.09,\n      brand: \"Samsung\",\n      insuranceCost: 8,\n    },\n    {\n      id: 104,\n      title: \"OPPOF19\",\n      description: \"OPPO F19 is officially announced on April 2021.\",\n      price: 280,\n      discountPercentage: 17.91,\n      rating: 4.3,\n      brand: \"Oppo\",\n      insuranceCost: 8,\n    },\n  ];\n\n  // priceAfterDiscount function\n  function priceAfterDiscount(price, discountPercentage) {\n    if (discountPercentage \u003c 0) {\n      console.log(\"Not a valid discount percentage\");\n      return 0;\n    } else {\n      // calculating price after discount\n      const discount = (price * discountPercentage) / 100;\n      return price - discount;\n    }\n  }\n\n  // printing product details\n  function printProductDetails(\n    pId,\n    pTitle,\n    pDescription,\n    pPrice,\n    pRating,\n    pBrand,\n    pDiscountPercentage\n  ) {\n    console.log(\"id : \" + pId);\n    console.log(\"title : \" + pTitle);\n    console.log(\"description : \" + pDescription);\n    console.log(\"rating : \" + pRating);\n    console.log(\"brand : \" + pBrand);\n    console.log(\"Original price : \" + pPrice + \" euros\");\n    console.log(\"Discount Percentage : \" + pDiscountPercentage);\n    console.log(\n      \"After the discount price : \" +\n        priceAfterDiscount(pPrice, pDiscountPercentage) +\n        \" euros\"\n    );\n  }\n\n  for (let index = 0; index \u003c products.length; index++) {\n    printProductDetails(\n      products[index].id,\n      products[index].title,\n      products[index].description,\n      products[index].price,\n      products[index].rating,\n      products[index].brand,\n      products[index].discountPercentage\n    );\n  }\n  ```\n\n- Program 10: E-commerce app [Pass object to a function]\n\n  ```js\n  // Program 10: E-commerce app [Pass object to a function]\n  const products = [\n    {\n      id: 101,\n      title: \"iphone 9\",\n      description: \"brilliant phone with 4k camera\",\n      price: 549,\n      discountPercentage: 8.5,\n      rating: 4.69,\n      brand: \"Apple\",\n      insuranceCost: 8,\n    },\n    {\n      id: 102,\n      title: \"iphone X\",\n      description:\n        \"SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...\",\n      price: 899,\n      discountPercentage: 17.94,\n      rating: 4.44,\n      brand: \"Apple\",\n      insuranceCost: 8,\n    },\n    {\n      id: 103,\n      title: \"Samsung Universe 9\",\n      description:\n        \"Samsung's new variant which goes beyond Galaxy to the Universe\",\n      price: 1249,\n      discountPercentage: 15.46,\n      rating: 4.09,\n      brand: \"Samsung\",\n      insuranceCost: 8,\n    },\n    {\n      id: 104,\n      title: \"OPPOF19\",\n      description: \"OPPO F19 is officially announced on April 2021.\",\n      price: 280,\n      discountPercentage: 17.91,\n      rating: 4.3,\n      brand: \"Oppo\",\n      insuranceCost: 8,\n    },\n  ];\n\n  // priceAfterDiscount function\n  function priceAfterDiscount(price, discountPercentage) {\n    if (discountPercentage \u003c 0) {\n      console.log(\"Not a valid discount percentage\");\n      return 0;\n    } else {\n      // calculating price after discount\n      const discount = (price * discountPercentage) / 100;\n      return price - discount;\n    }\n  }\n\n  // printing product details\n  function printProductDetails(product) {\n    console.log(\"id : \" + product.id);\n    console.log(\"title : \" + product.title);\n    console.log(\"description : \" + product.description);\n    console.log(\"rating : \" + product.rating);\n    console.log(\"brand : \" + product.brand);\n    console.log(\"Original price : \" + product.price + \" euros\");\n    console.log(\"Discount Percentage : \" + product.discountPercentage);\n    console.log(\n      \"After the discount price : \" +\n        priceAfterDiscount(product.price, product.discountPercentage) +\n        \" euros\"\n    );\n  }\n\n  for (let index = 0; index \u003c products.length; index++) {\n    printProductDetails(products[index]);\n    console.log(\"-------------------------\");\n  }\n  ```\n\n### 1.9 Built-in methods\n\n#### 1.9.1 Array Methods\n\nArray Methods: JavaScript provides a variety of built-in methods for working with arrays. These methods allow you to perform common operations on arrays, such as adding, removing, searching for elements, and transforming data. Example: push(), unshift(), pop(), shift(), concat(arr1,arr2), slice(startIndex,endIndex), splice(startIndex, deleteCount, item1...), forEach(callback), map(callback), filter(callback)\n\n1. **push(element1, element2, ...)**: Adds one or more elements to the end of an array and returns the new length of the array.\n\n   ```javascript\n   const fruits = [\"apple\", \"banana\"];\n   fruits.push(\"cherry\", \"date\");\n   // fruits is now ['apple', 'banana', 'cherry', 'date']\n   ```\n\n2. **pop()**: Removes and returns the last element from an array.\n\n   ```javascript\n   const fruits = [\"apple\", \"banana\", \"cherry\"];\n   const lastFruit = fruits.pop(); // 'cherry'\n   // fruits is now ['apple', 'banana']\n   ```\n\n3. **unshift(element1, element2, ...)**: Adds one or more elements to the beginning of an array and returns the new length of the array.\n\n   ```javascript\n   const fruits = [\"banana\", \"cherry\"];\n   fruits.unshift(\"apple\", \"date\");\n   // fruits is now ['apple', 'date', 'banana', 'cherry']\n   ```\n\n4. **shift()**: Removes and returns the first element from an array.\n\n   ```javascript\n   const fruits = [\"apple\", \"banana\", \"cherry\"];\n   const firstFruit = fruits.shift(); // 'apple'\n   // fruits is now ['banana', 'cherry']\n   ```\n\n5. **concat(array1, array2, ...)**: Combines two or more arrays and returns a new array without modifying the original arrays.\n\n   ```javascript\n   const arr1 = [1, 2];\n   const arr2 = [3, 4];\n   const combined = arr1.concat(arr2); // [1, 2, 3, 4]\n   ```\n\n6. **slice(startIndex, endIndex)**: Returns a shallow copy of a portion of an array as a new array. The `startIndex` is inclusive, and the `endIndex` is exclusive.\n\n   ```javascript\n   const fruits = [\"apple\", \"banana\", \"cherry\", \"date\"];\n   const sliced = fruits.slice(1, 3); // ['banana', 'cherry']\n   ```\n\n7. **splice(startIndex, deleteCount, item1, item2, ...)**: Changes the contents of an array by removing or replacing existing elements and/or adding new elements.\n\n   ```javascript\n   const fruits = [\"apple\", \"banana\", \"cherry\", \"date\"];\n   fruits.splice(2, 1, \"grape\", \"fig\");\n   // fruits is now ['apple', 'banana', 'grape', 'fig', 'date']\n   ```\n\n8. **forEach(callback)**: Calls a provided function once for each element in the array, in order.\n\n   ```javascript\n   const numbers = [1, 2, 3];\n   numbers.forEach((num) =\u003e {\n     console.log(num * 2);\n   });\n   // Output: 2, 4, 6\n   ```\n\n9. **map(callback)**: Creates a new array with the results of calling a provided function on every element in the array.\n\n   ```javascript\n   const numbers = [1, 2, 3];\n   const doubled = numbers.map((num) =\u003e num * 2);\n   // doubled is [2, 4, 6]\n   ```\n\n10. **filter(callback)**: Creates a new array with all elements that pass the test implemented by the provided function.\n\n    ```javascript\n    const numbers = [1, 2, 3, 4, 5];\n    const evens = numbers.filter((num) =\u003e num % 2 === 0);\n    // evens is [2, 4]\n    ```\n\n- array.sort() -\u003e [default sort string](https://www.w3schools.com/js/js_array_sort.asp)\n\n  ```js\n  const points = [40, 100, 1, 5, 25, 10];\n  points.sort(function (a, b) {\n    return a - b; // for reverse b-a\n  });\n  ```\n\n  - The compare function should return a negative, zero, or positive value, depending on the arguments:If the result is negative, a is sorted before b. If the result is positive, b is sorted before a. If the result is 0, no changes are done with the sort order of the two values.\n  - find lowest value: `points.sort(function(a, b){return b - a}); points[points.length-1]`\n  - sorting object arrays\n\n  ```js\n  const cars = [\n    { type: \"Volvo\", year: 2016 },\n    { type: \"Saab\", year: 2001 },\n    { type: \"BMW\", year: 2010 },\n  ];\n  cars.sort(function (a, b) {\n    return a.year - b.year;\n  });\n\n  // comparing string inside an object is complex\n  cars.sort(function (a, b) {\n    let x = a.type.toLowerCase();\n    let y = b.type.toLowerCase();\n    if (x \u003c y) {\n      return -1;\n    }\n    if (x \u003e y) {\n      return 1;\n    }\n    return 0;\n  });\n  ```\n\n- Example of a TODO APP\n\n```js\n// Initialize an empty array to store tasks\nconst tasks = [];\n\n// Function to add a task\nfunction addTask(task) {\n  tasks.push(task);\n  console.log(`Task \"${task}\" has been added.`);\n}\n\n// Function to list all tasks\nfunction listTasks() {\n  if (tasks.length === 0) {\n    console.log(\"No tasks found.\");\n  } else {\n    console.log(\"Tasks:\");\n    tasks.forEach((task, index) =\u003e {\n      console.log(`${index + 1}. ${task}`);\n    });\n  }\n}\n\n// Function to remove a task by its index\nfunction removeTask(index) {\n  if (index \u003e= 0 \u0026\u0026 index \u003c tasks.length) {\n    const removedTask = tasks.splice(index, 1)[0];\n    console.log(`Task \"${removedTask}\" has been removed.`);\n  } else {\n    console.log(\"Invalid task index.\");\n  }\n}\n\n// Example usage\naddTask(\"Buy groceries\");\naddTask(\"Read a book\");\nlistTasks();\nremoveTask(0);\nlistTasks();\n```\n\n#### 1.9.2 String Methods\n\nString Methods: JavaScript provides a variety of built-in methods for working with strings. These methods allow you to manipulate and transform strings in various ways. Here are some of the most commonly used string methods in JavaScript:\n\n1. **length**: Returns the length of a string.\n\n   ```javascript\n   const str = \"Hello, World!\";\n   const length = str.length; // 13\n   ```\n\n2. **charAt(index)**: Returns the character at the specified index in a string.\n\n   ```javascript\n   const str = \"JavaScript\";\n   const char = str.charAt(0); // 'J'\n   ```\n\n3. **charCodeAt(index)**: Returns the Unicode value of the character at the specified index in a string.\n\n   ```javascript\n   const str = \"JavaScript\";\n   const charCode = str.charCodeAt(0); // 74 (Unicode value for 'J')\n   ```\n\n4. **concat(str1, str2, ...)**: Combines two or more strings and returns a new concatenated string.\n\n   ```javascript\n   const str1 = \"Hello, \";\n   const str2 = \"World!\";\n   const result = str1.concat(str2); // 'Hello, World!'\n   ```\n\n5. **indexOf(substring, startIndex)**: Returns the index of the first occurrence of a substring in a string, or -1 if the substring is not found.\n\n   ```javascript\n   const str = \"Hello, World!\";\n   const index = str.indexOf(\"World\"); // 7\n   ```\n\n6. **lastIndexOf(substring, startIndex)**: Returns the index of the last occurrence of a substring in a string, or -1 if the substring is not found.\n\n   ```javascript\n   const str = \"Hello, World, World!\";\n   const index = str.lastIndexOf(\"World\"); // 13\n   ```\n\n7. **substring(startIndex, endIndex)**: Returns a new substring from a string. The `startIndex` is inclusive, and the `endIndex` is exclusive.\n\n   ```javascript\n   const str = \"Hello, World!\";\n   const substring = str.substring(7, 12); // 'World'\n   ```\n\n8. **slice(startIndex, endIndex)**: Returns a new substring from a string. The `startIndex` is inclusive, and the `endIndex` is exclusive. It works similarly to `substring`.\n\n   ```javascript\n   const str = \"Hello, World!\";\n   const sliced = str.slice(7, 12); // 'World'\n   ```\n\n9. **toUpperCase()**: Converts a string to uppercase.\n\n   ```javascript\n   const str = \"Hello, World!\";\n   const upperCaseStr = str.toUpperCase(); // 'HELLO, WORLD!'\n   ```\n\n10. **toLowerCase()**: Converts a string to lowercase.\n\n    ```javascript\n    const str = \"Hello, World!\";\n    const lowerCaseStr = str.toLowerCase(); // 'hello, world!'\n    ```\n\n11. **trim()**: Removes whitespace from the beginning and end of a string.\n\n    ```javascript\n    const str = \"   Hello, World!   \";\n    const trimmedStr = str.trim(); // 'Hello, World!'\n    ```\n\n12. **split(separator, limit)**: Splits a string into an array of substrings based on a specified separator.\n\n    ```javascript\n    const str = \"apple,banana,cherry\";\n    const fruits = str.split(\",\"); // ['apple', 'banana', 'cherry']\n    ```\n\n13. **replace(searchValue, replaceValue)**: Searches for a substring and replaces the first occurrence with a new substring.\n\n    ```javascript\n    const str = \"Hello, World!\";\n    const newStr = str.replace(\"World\", \"Universe\"); // 'Hello, Universe!'\n    ```\n\n14. **replaceAll(searchValue, replaceValue)**: Searches for all occurrences of a substring and replaces them with a new substring. (Introduced in ECMAScript 2021)\n\n    ```javascript\n    const str = \"apple apple apple\";\n    const newStr = str.replaceAll(\"apple\", \"banana\"); // 'banana banana banana'\n    ```\n\n#### 1.9.3 Number and Math Methods\n\nNumber Methods: JavaScript provides several methods for working with numbers. These methods allow you to perform common mathematical operations and manipulate numbers. Here are some commonly used Number methods in JavaScript:\n\n1. **toFixed(digits)**: Formats a number to a specified number of decimal places and returns it as a string.\n\n   ```javascript\n   const num = 12.3456;\n   const formattedNum = num.toFixed(2); // '12.35'\n   ```\n\n2. **toPrecision(precision)**: Formats a number to a specified total number of significant digits and returns it as a string.\n\n   ```javascript\n   const num = 123.4567;\n   const formattedNum = num.toPrecision(4); // '123.5'\n   ```\n\n3. **toString(radix)**: Converts a number to a string, optionally in a specified base (radix).\n\n   ```javascript\n   const num = 255;\n   const binaryStr = num.toString(2); // '11111111' (binary representation)\n   ```\n\n4. **parseInt(string, radix)**: Parses a string and returns an integer in the specified base (radix).\n\n   ```javascript\n   const binaryStr = \"101010\";\n   const decimalNum = parseInt(binaryStr, 2); // 42 (decimal)\n   ```\n\n5. **parseFloat(string)**: Parses a string and returns a floating-point number.\n\n   ```javascript\n   const floatStr = \"3.14159\";\n   const pi = parseFloat(floatStr); // 3.14159\n   ```\n\n6. **isNaN(value)**: Checks if a value is NaN (Not-a-Number).\n\n   ```javascript\n   isNaN(NaN); // true\n   isNaN(\"Hello\"); // true\n   isNaN(42); // false\n   ```\n\n7. **isFinite(value)**: Checks if a value is a finite number (not Infinity or -Infinity).\n\n   ```javascript\n   isFinite(42); // true\n   isFinite(Infinity); // false\n   ```\n\n8. **Number.isNaN(value)**: A more reliable way to check if a value is NaN.\n\n   ```javascript\n   Number.isNaN(NaN); // true\n   Number.isNaN(\"Hello\"); // false\n   ```\n\n9. **Number.isInteger(value)**: Checks if a value is an integer.\n\n   ```javascript\n   Number.isInteger(42); // true\n   Number.isInteger(3.14); // false\n   ```\n\n10. **Number.isSafeInteger(value)**: Checks if a value is a safe integer within the range of -2^53 to 2^53.\n\n    ```javascript\n    Number.isSafeInteger(9007199254740992); // false\n    ```\n\n11. **Math.abs(value)**: Returns the absolute (positive) value of a number.\n\n    ```javascript\n    Math.abs(-42); // 42\n    ```\n\n12. **Math.round(value)**: Rounds a number to the nearest integer.\n\n    ```javascript\n    Math.round(3.49); // 3\n    Math.round(3.5); // 4\n    ```\n\n13. **Math.floor(value)**: Rounds a number down to the nearest integer.\n\n    ```javascript\n    Math.floor(3.9); // 3\n    ```\n\n14. **Math.ceil(value)**: Rounds a number up to the nearest integer.\n\n    ```javascript\n    Math.ceil(3.1); // 4\n    ```\n\n15. **Math.min(...values)**: Returns the smallest number from a list of values.\n\n    ```javascript\n    Math.min(5, 2, 9, 1); // 1\n    ```\n\n16. **Math.max(...values)**: Returns the largest number from a list of values.\n\n    ```javascript\n    Math.max(5, 2, 9, 1); // 9\n    ```\n\n17. **Math.trunc()**: returns the integer part. `Math.trunc(4.6)=4; Math.trunc(4.5)=4, Math.trunc(-4.4)=-4`\n\n18. **Math.random()**: returns a random number between 0 (inclusive), and 1 (exclusive)\n\n```js\nconsole.log(Math.random());\nconst randomNumber = Math.floor(Math.random() * 5) + 1;\n```\n\n#### 1.9.4 Date Methods\n\n- given year, month and day find the day\n\n```js\nconst date = new Date();\nconsole.log(date.getFullYear());\nconsole.log(date.getMonth());\nconsole.log(date.getDate());\nconsole.log(date.getDay());\nconsole.log(date.getHours());\nconsole.log(date.getMinutes());\nconsole.log(date.getSeconds());\nconsole.log(date.getMilliseconds());\n\n// give year, month, day -\u003e 2020, 5, 12\n// find the day name -\u003e Friday\nfunction getWeekDay(year, month, day) {\n  const names = [\n    \"Sunday\",\n    \"Monday\",\n    \"Tuesday\",\n    \"Wednesday\",\n    \"Thursday\",\n    \"Friday\",\n    \"Saturday\",\n  ];\n  const date = new Date(year, month, day);\n  //complete the function\n  return names[date.getDay()];\n}\n\nconsole.log(date);\nconsole.log(date.toDateString()); // return a date object into readbale string\nconsole.log(date.toISOString()); // return a date object into iso standard\nconsole.log(date.toLocaleString()); // return a date object into iso standard\n```\n\n- Program 11: E-Commerce app [Math methods]\n\n```js\n// Program 11: E-commerce app [Math methods]\nconst products = [\n  {\n    id: 101,\n    title: \"iphone 9\",\n    description: \"brilliant phone with 4k camera\",\n    price: 549,\n    discountPercentage: 8.5,\n    rating: 4.69,\n    brand: \"Apple\",\n    insuranceCost: 8,\n  },\n  {\n    id: 102,\n    title: \"iphone X\",\n    description:\n      \"SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...\",\n    price: 899,\n    discountPercentage: 17.94,\n    rating: 4.44,\n    brand: \"Apple\",\n    insuranceCost: 8,\n  },\n  {\n    id: 103,\n    title: \"Samsung Universe 9\",\n    description:\n      \"Samsung's new variant which goes beyond Galaxy to the Universe\",\n    price: 1249,\n    discountPercentage: 15.46,\n    rating: 4.09,\n    brand: \"Samsung\",\n    insuranceCost: 8,\n  },\n  {\n    id: 104,\n    title: \"OPPOF19\",\n    description: \"OPPO F19 is officially announced on April 2021.\",\n    price: 280,\n    discountPercentage: 17.91,\n    rating: 4.3,\n    brand: \"Oppo\",\n    insuranceCost: 8,\n  },\n];\n\n// priceAfterDiscount function\nfunction priceAfterDiscount(price, discountPercentage) {\n  if (discountPercentage \u003c 0) {\n    console.log(\"Not a valid discount percentage\");\n    return 0;\n  } else {\n    // calculating price after discount\n    const discount = (price * discountPercentage) / 100;\n    return Math.round(price - discount);\n  }\n}\n\n// printing product details\nfunction printProductDetails(product) {\n  console.log(\"id : \" + product.id);\n  console.log(\"title : \" + product.title);\n  console.log(\"description : \" + product.description);\n  console.log(\"rating : \" + product.rating);\n  console.log(\"brand : \" + product.brand);\n  console.log(\"Original price : \" + product.price + \" euros\");\n  console.log(\"Discount Percentage : \" + product.discountPercentage);\n  console.log(\n    \"After the discount price : \" +\n      priceAfterDiscount(product.price, product.discountPercentage) +\n      \" euros\"\n  );\n}\n\nfor (let index = 0; index \u003c products.length; index++) {\n  printProductDetails(products[index]);\n  console.log(\"-------------------------\");\n}\n```\n\n### 1.10 Errors and errors Handling\n\nIn JavaScript, errors can be categorized into several types based on their origins and characteristics. Here are some common types of errors in JavaScript:\n\n1. **Syntax Errors:**\n\n   - **Description:** These errors occur when there are issues with the syntax of your JavaScript code. For example, missing parentheses, semicolons, or incorrect variable names.\n   - **Example:**\n\n     ```javascript\n     if (x \u003e 5  // Missing closing parenthesis\n       console.log(\"Hello, World\");\n     ```\n\n2. **Reference Errors:**\n\n   - **Description:** Reference errors happen when you try to access a variable or function that has not been declared or is not in scope.\n   - **Example:**\n\n     ```javascript\n     console.log(y); // ReferenceError: y is not defined\n     ```\n\n3. **Type Errors:**\n\n   - **Description:** Type errors occur when you try to perform an operation on a value that is of the wrong type.\n   - **Example:**\n\n     ```javascript\n     let x = \"Hello\";\n     x.toUpperCase(); // TypeError: x.toUpperCase is not a function\n     ```\n\n4. **Range Errors:**\n\n   - **Description:** These errors occur when you try to manipulate a value that is outside the allowable range.\n   - **Example:**\n\n     ```javascript\n     let arr = [1, 2, 3];\n     arr[5] = 6; // RangeError: Invalid array length\n     ```\n\n5. **Custom Errors:**\n\n   - **Description:** You can create custom errors in JavaScript by extending the built-in `Error` object. This is often done to provide more context-specific error messages.\n   - **Example:**\n\n     ```javascript\n     class MyError extends Error {\n       constructor(message) {\n         super(message);\n         this.name = \"MyError\";\n       }\n     }\n\n     throw new MyError(\"This is a custom error.\");\n     ```\n\n6. **Network Errors:**\n\n   - **Description:** These errors occur when there are issues with network requests, such as failed fetch requests due to network problems.\n   - **Example:**\n\n     ```javascript\n     fetch(\"https://example.com/api\")\n       .then((response) =\u003e response.json())\n       .catch((error) =\u003e console.error(error)); // NetworkError: Failed to fetch\n     ```\n\n7. **Promise Errors:**\n\n   - **Description:** When working with Promises, errors can occur during Promise rejection.\n   - **Example:**\n\n     ```javascript\n     new Promise((resolve, reject) =\u003e {\n       reject(\"Promise rejected\");\n     }).catch((error) =\u003e console.error(error)); // \"Promise rejected\"\n     ```\n\n8. **Eval Errors:**\n\n   - **Description:** Eval errors occur when using the `eval()` function and there is an issue with the evaluated code.\n   - **Example:**\n\n     ```javascript\n     eval(\"var x = 1;\");\n     console.log(x); // ReferenceError: x is not defined\n     ```\n\n9. **Internal Errors:**\n   - **Description:** These errors are typically thrown by the JavaScript engine itself and indicate a critical issue in the engine or runtime environment.\n   - **Example:** Usually, you won't encounter these directly in your code.\n\n- compile time error vs run time error. runnable program can be handled by try, catch, finally, throw (defines a custom error)\n\n  ```js\n  // without try,catch\n  alert(\"hello\");\n  alert(num);\n  alert(\"bye\");\n\n  // with try-catch\n  try {\n    alert(\"hello\");\n    alert(num);\n    alert(\"bye\");\n  } catch (error) {\n    console.log(\"inside catch block\");\n    console.log(error);\n    console.log(error.name);\n    console.log(error.message);\n  } finally {\n    alert(\"bye\");\n  }\n\n\n  \u003c!-- The throw statement allows you to create a custom error. --\u003e\n  throw \"not valid input\"\n  throw 0\n  throw {message: 'wrong input'}\n  throw true\n\n  fullName = \"anisul islam\"; // Uncaught ReferenceError: fullName is not defined\n  // this is a run time error\n  console.log(fullName);\n\n  const user = {\n    fullName: \"anisul islam\",\n  };\n  console.log(user.age); // reference error\n\n  console.log(user..age) // syntax error\n\n  const number = 20;\n  number = 30; // type error\n  console.log(number);\n\n  try {\n    console.log(\"hi\");\n    alert(nationality);\n    console.log(\"hello\");\n  } catch (err) {\n    // console.log(err);\n    // console.warn(err);\n    // console.error(err.name);\n    // console.error(err.message);\n    console.error(err.stack); // return details\n  }\n  console.log(\"bye\");\n  ```\n\n- Adding try-catch in todo application\n\n  ```js\n  // Initialize an empty array to store tasks\n  const tasks = [];\n\n  // Function to add a task\n  function addTask(task) {\n    tasks.push(task);\n    console.log(`Task \"${task}\" has been added.`);\n  }\n\n  // Function to list all tasks\n  function listTasks() {\n    if (tasks.length === 0) {\n      console.log(\"No tasks found.\");\n    } else {\n      console.log(\"Tasks:\");\n      tasks.forEach((task, index) =\u003e {\n        console.log(`${index + 1}. ${task}`);\n      });\n    }\n  }\n\n  // Function to remove a task by its index\n  function removeTask(index) {\n    try {\n      if (index \u003e= 0 \u0026\u0026 index \u003c tasks.length) {\n        const removedTask = tasks.splice(index, 1)[0];\n        console.log(`Task \"${removedTask}\" has been removed.`);\n      } else {\n        throw new Error(\"Invalid task index.\");\n      }\n    } catch (error) {\n      console.log(error.message);\n    }\n  }\n\n  // Example usage\n  addTask(\"Buy groceries\");\n  addTask(\"Read a book\");\n  listTasks();\n  removeTask(0); // Valid index\n  listTasks();\n  removeTask(2); // Invalid index\n  ```\n\n- Program 12: E-commerce app [Error handling]\n\n```js\nconst products = [\n  {\n    id: 101,\n    title: \"iphone 9\",\n    description: \"brilliant phone with 4k camera\",\n    price: 549,\n    discountPercentage: 8.5,\n    rating: 4.69,\n    brand: \"Apple\",\n    insuranceCost: 8,\n  },\n  {\n    id: 102,\n    title: \"iphone X\",\n    description:\n      \"SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...\",\n    price: 899,\n    discountPercentage: 17.94,\n    rating: 4.44,\n    brand: \"Apple\",\n    insuranceCost: 8,\n  },\n  {\n    id: 103,\n    title: \"Samsung Universe 9\",\n    description:\n      \"Samsung's new variant which goes beyond Galaxy to the Universe\",\n    price: 1249,\n    discountPercentage: 15.46,\n    rating: 4.09,\n    brand: \"Samsung\",\n    insuranceCost: 8,\n  },\n  {\n    id: 104,\n    title: \"OPPOF19\",\n    description: \"OPPO F19 is officially announced on April 2021.\",\n    price: 280,\n    discountPercentage: 17.91,\n    rating: 4.3,\n    brand: \"Oppo\",\n    insuranceCost: 8,\n  },\n];\n\n// priceAfterDiscount function\nfunction priceAfterDiscount(price, discountPercentage) {\n  if (discountPercentage \u003c 0) {\n    throw new Error(\"Invalid discount percentage\"); // Throw an error for invalid input\n  } else {\n    // calculating price after discount\n    const discount = (price * discountPercentage) / 100;\n    return Math.round(price - discount);\n  }\n}\n\n// printing product details\nfunction printProductDetails(product) {\n  console.log(\"id : \" + product.id);\n  console.log(\"title : \" + product.title);\n  console.log(\"description : \" + product.description);\n  console.log(\"rating : \" + product.rating);\n  console.log(\"brand : \" + product.brand);\n  console.log(\"Original price : \" + product.price + \" euros\");\n  console.log(\"Discount Percentage : \" + product.discountPercentage);\n\n  try {\n    const discountedPrice = priceAfterDiscount(\n      product.price,\n      product.discountPercentage\n    );\n    console.log(\"After the discount price : \" + discountedPrice + \" euros\");\n  } catch (error) {\n    console.error(\"Error: \" + error.message); // Handle and log errors\n  }\n\n  console.log(\"-------------------------\");\n}\n\nfor (let index = 0; index \u003c products.length; index++) {\n  printProductDetails(products[index]);\n  console.log(\"-------------------------\");\n}\n```\n\n### 1.11 JSON and JSDoc\n\n- JSON (JavaScript Object Notation) is a lightweight data-interchange format that is commonly used for data serialization and communication between a server and a web application, as well as for configuration files and data storage. In JavaScript, JSON is a text-based format that can be represented as a string and parsed into JavaScript objects or used to serialize JavaScript objects into strings.\n\n  - Here are some key aspects of JSON in JavaScript:\n\n    1. **JSON Syntax:**\n\n       - JSON data consists of key-value pairs.\n       - Keys must be strings enclosed in double quotation marks.\n       - Values can be strings, numbers, objects, arrays, booleans, or `null`.\n       - Data is separated by commas, and key-value pairs are separated by colons.\n       - JSON objects are enclosed in curly braces `{}`.\n       - JSON arrays are ordered lists of values enclosed in square brackets `[]`.\n\n         ```javascript\n         {\n           \"name\": \"John\",\n           \"age\": 30,\n           \"isStudent\": false,\n           \"hobbies\": [\"Reading\", \"Swimming\"],\n           \"address\": {\n             \"city\": \"New York\",\n             \"zipCode\": \"10001\"\n           }\n         }\n         ```\n\n    2. **JSON.parse():**\n\n       - The `JSON.parse()` method is used to parse a JSON string and convert it into a JavaScript object.\n       - It takes a JSON string as an argument and returns the corresponding JavaScript object.\n\n         ```javascript\n         const jsonString = '{\"name\": \"Alice\", \"age\": 25}';\n         const person = JSON.parse(jsonString);\n         console.log(person.name); // \"Alice\"\n         ```\n\n    3. **JSON.stringify():**\n\n       - The `JSON.stringify()` method is used to serialize a JavaScript object into a JSON string.\n       - It takes a JavaScript object as an argument and returns the corresponding JSON string.\n\n         ```javascript\n         const person = { name: \"Bob\", age: 30 };\n         const jsonString = JSON.stringify(person);\n         console.log(jsonString); // '{\"name\":\"Bob\",\"age\":30}'\n         ```\n\n    4. **Working with JSON Arrays:**\n\n       - JSON can represent arrays of data.\n       - JSON arrays are ordered lists enclosed in square brackets `[]`.\n\n         ```javascript\n         const numbers = [1, 2, 3, 4, 5];\n         const jsonArray = JSON.stringify(numbers);\n         console.log(jsonArray); // '[1,2,3,4,5]'\n         ```\n\n    JSON is a widely used data format for exchanging and storing structured data. It's supported in many programming languages, making it a popular choice for data interchange in web applications and APIs. In JavaScript, the `JSON.parse()` and `JSON.stringify()` methods make it easy to work with JSON data.\n\n  - JSON VS JS Object\n    - key with double quotation\n    - JSON can not contain function but JS Object does\n    - JS Object is only for JS but JSON for all other programming languages\n  - client-server conversion\n\n    - Before using json data in client convert into JS Object -\u003e JSON.parse()\n\n      ```js\n      // json object\n      const jsonData = '{ \"name\": \"John\", \"age\": 22 }';\n\n      // converting to JavaScript object\n      const obj = JSON.parse(jsonData);\n\n      // accessing the data\n      console.log(obj.name); // John\n      ```\n\n    - Before sending to server convert into JSON -\u003e JSON.stringify()\n\n      ```js\n      // JavaScript object\n      const jsonData = { name: \"John\", age: 22 };\n\n      // converting to JSON\n      const obj = JSON.stringify(jsonData);\n\n      // accessing the data\n      console.log(obj); // \"{\"name\":\"John\",\"age\":22}\"\n      ```\n\n- [jsdoc](https://github.com/anisul-Islam/jsdoc-documentation)\n\n  - Program 13: E-Commerce app [adding jsdoc]\n\n    ```js\n    /**\n     * product id\n     * @type {number}\n     */\n    const id = 101;\n    const title = \"iphone 12\";\n    const description = \"brilliant phone with 4k camera\";\n    const price = 549;\n    const discountPercentage = 8.5;\n    const rating = 4.69;\n    const brand = \"Apple\";\n\n    const insuranceCost = 8;\n\n    /**\n     * calculate the discount amount of a product\n     * @param {number} p The product price\n     * @param {number} disPercentage The discount percentage of the product\n     * @returns the discount amount\n     */\n    const discount = (p, disPercentage) =\u003e (p * disPercentage) / 100;\n\n    /**\n     * calculate the round value of any amount\n     * @param {number} p The product price\n     * @returns the rounded value\n     */\n    const roundPrice = (p) =\u003e Math.round(p);\n\n    /**\n     * calculate the priceAfterDiscount\n     * @param {number} p The product price\n     * @param {number} dp discount percentage\n     * @returns the price after discount\n     */\n    const priceAfterDiscount = (p, dp) =\u003e p - discount(p, dp);\n\n    /**\n     * calculate the product finalPriceWithInsurance\n     * @param {number} p the price of product;\n     * @param {number} dp the discount percentage of prodcut;\n     * @param {number} ic the product insurance cost\n     * @returns the final price including insurance cost\n     */\n    const finalPriceWithInsurance = (p, dp, ic) =\u003e\n      roundPrice(priceAfterDiscount(p, dp) + ic);\n\n    /**\n     * print product details\n     * @param {number} pId the product id\n     * @param {string} pTitle the product title\n     * @param {string} pDescription the product description\n     * @param {number} pPrice the product price\n     * @param {number} pRating the product rating\n     * @param {string} pBrand the product brand\n     * @param {number} PDiscountPercentage the discount percentage of the product\n     * @param {number} pInsurance the insurance cost of the product\n     */\n    const printProductDetails = (\n      pId,\n      pTitle,\n      pDescription,\n      pPrice,\n      pRating,\n      pBrand,\n      PDiscountPercentage,\n      pInsurance\n    ) =\u003e {\n      console.log(`id : ${pId}`);\n      console.log(`title : ${pTitle}`);\n      console.log(`description: ${pDescription}`);\n      console.log(`price : ${pPrice} euros`);\n      console.log(`rating : ${pRating}`);\n      console.log(`brand : ${pBrand}`);\n      console.log(\n        `finalPriceWithInsurance : ${finalPriceWithInsurance(\n          pPrice,\n          PDiscountPercentage,\n          pInsurance\n        )} euros`\n      );\n    };\n\n    printProductDetails(\n      id,\n      title,\n      description,\n      price,\n      rating,\n      brand,\n      discountPercentage,\n      insuranceCost\n    );\n    ```\n\n[\u0026#8593; Back to Top](#table-of-contents)\n\n## 2. Intermediate Javascript Topics\n\n### 2.1 Document Object Model (DOM) and Events\n\nThe Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content dynamically. In other words, it allows you to interact with the content and structure of a web page using JavaScript. The DOM is a tree-like structure, where each node represents part of the web page.\n\nHere are some key concepts and operations related to the DOM in JavaScript:\n\n**1. Accessing Elements:**\n\n- You can access HTML elements in JavaScript using methods like `getElementById`, `getElementsByClassName`, `getElementsByTagName`, and `querySelector`. For example:\n\n```javascript\nconst elementById = document.getElementById(\"myElement\");\nconst elementsByClass = document.getElementsByClassName(\"myClass\");\nconst elementsByTag = document.getElementsByTagName(\"div\");\nconst elementBySelector = document.querySelector(\".myClass\");\n```\n\n**2. Modifying Elements:**\n\n- You can change element properties, attributes, and content using JavaScript. For example:\n\n```javascript\nelementById.innerHTML = \"New Content\";\nelementById.style.color = \"red\";\nelementById.setAttribute(\"data-custom\", \"value\");\n```\n\n**3. Creating Elements:**\n\n- You can create new HTML elements dynamically and add them to the DOM. For example:\n\n```javascript\nconst newDiv = document.createElement(\"div\");\nnewDiv.textContent = \"Dynamic Element\";\ndocument.body.appendChild(newDiv);\n```\n\n**4. Removing Elements:**\n\n- You can remove elements from the DOM using the `removeChild` or `remove` methods. For example:\n\n```javascript\nconst elementToRemove = document.getElementById(\"toRemove\");\nelementToRemove.parentNode.removeChild(elementToRemove);\n```\n\n**5. Event Handling:**\n\n- You can attach event listeners to elements to respond to user interactions. For example:\n\n```javascript\nconst button = document.getElementById(\"myButton\");\nbutton.addEventListener(\"click\", function () {\n  alert(\"Button Clicked!\");\n});\n```\n\n**6. Traversing the DOM:**\n\n- You can navigate the DOM tree by accessing parent, child, and sibling nodes. For example:\n\n```javascript\nconst parent = element.parentNode;\nconst firstChild = parent.firstChild;\nconst nextSibling = element.nextSibling;\n```\n\n**7. Working with Forms:**\n\n- You can access and manipulate form elements and their values. For example:\n\n```javascript\nconst inputField = document.getElementById(\"username\");\nconst inputValue = inputField.value;\n```\n\n**8. Styling Elements:**\n\n- You can change the style of elements using the `style` property. For example:\n\n```javascript\nelement.style.color = \"blue\";\nelement.style.fontSize = \"18px\";\n```\n\n**9. DOM Events:**\n\n- The DOM provides a wide range of events like click, mouseover, change, and more. You can use these events to trigger JavaScript functions in response to user actions.\n\nThe DOM is a fundamental concept in web development because it enables dynamic and interactive web pages. It's a crucial part of JavaScript programming for the web.\n\n#### Event and event listeners\n\n- keyboard event\n\n  ```js\n  // KeyboardEvent Object\n  // 1. Keydown - pressing a key, can repeat\n  // 2. keypress (may not supported by some browsers)\n  // 3. keyup\n  // some properties - key, keyCode, code, shiftKey, ctlKey, repeat\n\n  const textarea = document.querySelector(\"textarea\");\n  textarea.addEventListener(\"keydown\", function (e) {\n    if (e.repeat) {\n      alert(\"do not repeat\");\n    }\n  });\n  // textarea.addEventListener(\"keypress\", function () {\n  //   console.log(\"keypress\");\n  // });\n  // textarea.addEventListener(\"keyup\", function (e) {\n  //   if (e.shiftKey) {\n  //     console.log(\"shift+\" + e.key);\n  //   }\n  // });\n  ```\n\n- Mouse event\n\n  ```js\n  // MouseEvent - \u003chtml\u003e, \u003chead\u003e, \u003cmeta\u003e, \u003ctitle\u003e, \u003cbr\u003e, \u003cstyle\u003e, \u003cscript\u003e, \u003ciframe\u003e, \u003cparam\u003e, \u003cbase\u003e, \u003cbdo\u003e\n  // 1. onclick\n  // 2. ondblclick\n  // 3. onmousedown\n  // 4. onmousedup\n  // 5. onmouseenter\n  // 6. onmouseleave\n  // 7. onmousemove\n  // 8. onmouseover\n\n  console.clear();\n  const div = document.querySelector(\"div\");\n\n  div.addEventListener(\"click\", function (e) {\n    //   console.log(\"click is occured\");\n    //   console.log(e.target);\n    //   console.log(e.target.id);\n    //   console.log(e.target.className);\n    //   console.log(e.target.innerHTML);\n    //   console.log(e.target.innerText);\n    //   console.log(e.target.textContent);\n  });\n\n  // div.addEventListener(\"dblclick\", function () {\n  //   console.log(\"dblclick is occured\");\n  // });\n  // div.addEventListener(\"mousedown\", function () {\n  //   console.log(\"mousedown is occured\");\n  // });\n  // div.addEventListener(\"mouseup\", function () {\n  //   console.log(\"mouseup is occured\");\n  // });\n  // div.addEventListener(\"mouseenter\", function () {\n  //   console.log(\"mouseenter is occured\");\n  // });\n  // div.addEventListener(\"mouseleave\", function () {\n  //   console.log(\"mouseleave is occured\");\n  // });\n  // div.addEventListener(\"mouseover\", function () {\n  //   console.log(\"mouseover is occured\");\n  // });\n  // div.addEventListener(\"mousemove\", function (e) {\n  //   //   console.log(\"mousemove is occured\");\n  //   //   console.log(\"clientX = \" + e.clientX + \", clientY = \" + e.clientY);\n  //   console.log(\"offsetX = \" + e.offsetX + \", offsetY = \" + e.offsetY);\n  // });\n\n  const buttons = document.querySelectorAll(\".btn\");\n\n  Array.from(buttons).map((button) =\u003e {\n    button.addEventListener(\"click\", function (e) {\n      console.log(e.target.innerText);\n    });\n  });\n  ```\n\n- onchange event\n\n  ```js\n  // \u003cinput /\u003e - text, number, password, email, color,  radio, checkbox, search, time, date, datetime, week, month, url, tel, file,\n  // \u003cselect\u003e,\n  // \u003ctextarea\u003e\n\n  console.clear();\n  // const input = document.querySelector(\"input[name=name]\");\n  // input.addEventListener(\"change\", changeHandler);\n\n  // function changeHandler(e) {\n  //   //   console.log(e);\n  //   //   console.log(e.type);\n  //   //   console.log(e.target);\n  //   //   console.log(e.target.className);\n  //   //   console.log(e.target.id);\n  //   console.log(e.target.value);\n  // }\n\n  // const programs = document.querySelectorAll(\"input[name=program]\");\n  // console.log(programs);\n\n  // Array.from(programs).map((program) =\u003e {\n  //   program.addEventListener(\"change\", programHandler);\n  // });\n\n  // function programHandler(e) {\n  //   if (e.target.checked) {\n  //     console.log(e.target.value);\n  //   }\n  // }\n\n  const department = document.querySelector(\"#department\");\n  // console.log(department);\n\n  department.addEventListener(\"change\", handleDepartment);\n\n  function handleDepartment(e) {\n    console.log(e.target.value);\n  }\n  ```\n\n- onsubmit event\n\n  ```js\n  // finding the elements\n  const form = document.querySelector(\"form\");\n  const name = form.querySelector(\"div #name\");\n  const email = form.querySelector(\"div #email\");\n  const password = form.querySelector(\"div #password\");\n\n  form.addEventListener(\"submit\", formHandler);\n\n  function formHandler(e) {\n    e.preventDefault();\n\n    const userInfo = {\n      name: name.value,\n      email: email.value,\n      password: password.value,\n    };\n\n    console.log(userInfo);\n    name.value = \"\";\n    email.value = \"\";\n    password.value = \"\";\n  }\n  ```\n\n[\u0026#8593; Back to Top](#table-of-contents)[\u0026#8593; Back to Top](#table-of-contents)\n\n[\u0026#8593; Back to Top](#table-of-contents)\n\n### 2.2 Browser Object Model (BOM)\n\n- BOM allows javascript to speak or communicate with broswer\n\n  - popup boxes\n\n  ```js\n  console.clear();\n  console.log(window);\n  console.log(window.location); // return current page url\n  console.log(window.location.href); // return entire url\n  console.log(window.location.protocol); // return protocol\n  console.log(window.location.hostname); // return hostname\n  console.log(window.location.port); // return port\n  console.log(window.location.pathname); // return pathname\n  ```\n\n- popup boxes -\u003e alert(), confirm(), prompt()\n\n  ```js\n  const deleteUser = () =\u003e {\n    const value = confirm(\"Do you want to Delete the user? \");\n    if (value) {\n      console.log(\"user is deleted\");\n    } else {\n      console.log(\"user is not deleted\");\n    }\n  };\n\n  deleteUser();\n  ```\n\n- Timing event methods -\u003e setTimeout(), setInterval()\n\n  - if you want to do something after a specific time then we can take help of setTimeout(), setInterval() from window object\n\n  ```js\n  const getAllUsers = () =\u003e {\n    const users = [\n      {\n        id: 1,\n        name: \"anisul islam\",\n      },\n      {\n        id: 2,\n        name: \"Robert william\",\n      },\n    ];\n    console.log(users);\n  };\n\n  setTimeout(getAllUsers, 2000);\n\n  // setInterval() repeats after certain period of time\n  setInterval(() =\u003e {\n    const users = [\n      {\n        id: 1,\n        name: \"anisul islam\",\n      },\n      {\n        id: 2,\n        name: \"Robert william\",\n      },\n    ];\n    console.log(users);\n  }, 2000);\n  ```\n\n[\u0026#8593; Back to Top](#table-of-contents)\n\n[\u0026#8593; Back to Top](#table-of-contents)\n\n### 2.3 Local storage\n\n```js\n// Web storage API - allows us to store \u0026 read data in browser\n// Web storage API - localStorage, sessionStorage\n\n// localStorage - store, read, update and remove data\n// no expiry date: data never gets lost even if you close the browser\n\n// localStorage store data as key value pair - string\n\n// setItem(key, value)\n// localStorage.setItem(\"userName\", \"anisul islam\");\n// localStorage.setItem(\"password\", \"0123456789\");\n\n// getItem(key)\n// const userName = localStorage.getItem(\"userName\");\n// const userPassword = localStorage.getItem(\"password\");\n// console.log(userName, userPassword);\n\n// removeItem(key)\n// localStorage.removeItem(\"userName\");\n// localStorage.removeItem(\"password\");\n\n// setItem(key, value)\n// const countries = [\"Australia\", \"Bangladesh\", \"Nepal\"];\n// localStorage.setItem(\"countries\", JSON.stringify(countries));\n\n// // getItem(key)\n// const countriesList = JSON.parse(localStorage.getItem(\"countries\"));\n// console.log(countriesList);\n\n// localStorage.clear();\n```\n\n[\u0026#8593; Back to Top](#table-of-contents)\n\n[\u0026#8593; Back to Top](#t","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flearnwithfair%2Fjavascript-documentation","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flearnwithfair%2Fjavascript-documentation","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flearnwithfair%2Fjavascript-documentation/lists"}