{"id":62506,"url":"https://github.com/lifeparticle/JS-Cheatsheet","name":"JS-Cheatsheet","description":"🖥 Cheatsheet for JavaScript","projects_count":36,"last_synced_at":"2026-06-09T09:00:26.999Z","repository":{"id":39223125,"uuid":"392145437","full_name":"lifeparticle/JS-Cheatsheet","owner":"lifeparticle","description":"🖥 Cheatsheet for JavaScript","archived":false,"fork":false,"pushed_at":"2025-02-05T01:55:16.000Z","size":1978,"stargazers_count":22,"open_issues_count":2,"forks_count":5,"subscribers_count":2,"default_branch":"main","last_synced_at":"2026-05-23T18:03:20.728Z","etag":null,"topics":["awesome","challenges","cheatsheet","chrome-extension","electron","eslint","examples","javascript","js","nodejs","npm","pnpm","reactjs","typescript","yarn"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/lifeparticle.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","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,"zenodo":null},"funding":{"github":["lifeparticle"],"patreon":null,"open_collective":null,"ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"lfx_crowdfunding":null,"custom":null}},"created_at":"2021-08-03T01:19:39.000Z","updated_at":"2025-10-31T04:49:28.000Z","dependencies_parsed_at":"2025-04-23T03:11:18.731Z","dependency_job_id":null,"html_url":"https://github.com/lifeparticle/JS-Cheatsheet","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/lifeparticle/JS-Cheatsheet","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lifeparticle%2FJS-Cheatsheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lifeparticle%2FJS-Cheatsheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lifeparticle%2FJS-Cheatsheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lifeparticle%2FJS-Cheatsheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lifeparticle","download_url":"https://codeload.github.com/lifeparticle/JS-Cheatsheet/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lifeparticle%2FJS-Cheatsheet/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34098952,"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-09T02:00:06.510Z","response_time":63,"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"}},"created_at":"2024-07-02T00:00:22.141Z","updated_at":"2026-06-09T09:00:27.000Z","primary_language":null,"list_of_lists":false,"displayable":true,"categories":["Breakpoints","string","Two-dimensional array","A non-pure function","Uncategorized","for...of","Scope","number","Regular / Named function","Getters and Setters","Event handling"],"sub_categories":["40. toSpliced","Methods and properties","Event capturing","Uncategorized","Local scope"],"readme":"# Table of Contents\n\n- [History of JavaScript](#history-of-javascript)\n- [Introduction](#introduction)\n- [JavaScript runtimes](#javascript-runtimes)\n- [Reserved words](#reserved-words)\n- [Comments](#comments)\n- [Variables](#variables)\n\t* [undefined and null](#undefined-and-null)\n\t* [Leaked variables](#leaked-variables)\n\t* [Scope](#scope)\n\t\t+ [Global scope](#global-scope)\n\t\t+ [Local scope](#local-scope)\n\t\t\t- [Function block](#function-block)\n\t\t\t- [if block](#if-block)\n\t\t\t- [Hoisting](#hoisting)\n- [Data types](#data-types)\n\t* [How to check the data type](#how-to-check-the-data-type)\n\t* [Type coercion](#type-coercion)\n\t* [string](#string)\n\t\t+ [Methods and properties](#methods-and-properties)\n\t\t+ [Template strings](#template-strings)\n\t\t+ [Escape charecters](#escape-charecters)\n\t* [number](#number)\n\t\t+ [Methods and properties](#methods-and-properties)\n\t* [bigint](#bigint)\n\t* [symbol](#symbol)\n\t* [undefind](#undefind)\n\t* [null](#null)\n\t* [object](#object)\n\t\t+ [Empty object.](#empty-object)\n\t\t+ [Equality](#equality)\n\t\t+ [Object with properties and values.](#object-with-properties-and-values)\n\t\t+ [Object reference](#object-reference)\n\t\t+ [Get all the keys.](#get-all-the-keys)\n\t\t+ [Get all the values.](#get-all-the-values)\n\t\t+ [Checking properties.](#checking-properties)\n\t\t+ [Get all the keys and values.](#get-all-the-keys-and-values)\n\t\t+ [Object destructuring](#object-destructuring)\n\t\t+ [Object property shorthand](#object-property-shorthand)\n\t\t+ [Spread syntax (...)](#spread-syntax-)\n\t\t+ [Rest syntax (parameters) (...)](#rest-syntax-parameters-)\n\t\t+ [object Spread syntax](#object-spread-syntax)\n\t\t+ [Delete properties](#delete-properties)\n\t\t+ [Group by](#group-by)\n- [Array](#array)\n\t* [Array methods](#array-methods)\n\t\t+ [1. at](#1-at)\n\t\t+ [2. concat](#2-concat)\n\t\t+ [5. every](#5-every)\n\t\t+ [6. fill](#6-fill)\n\t\t+ [7. filter](#7-filter)\n\t\t+ [8. findIndex](#8-findindex)\n\t\t+ [9. find](#9-find)\n\t\t+ [12. forEach](#12-foreach)\n\t\t+ [14. includes](#14-includes)\n\t\t+ [15. indexOf](#15-indexof)\n\t\t+ [17. join](#17-join)\n\t\t+ [19. lastIndexOf](#19-lastindexof)\n\t\t+ [20. map](#20-map)\n\t\t+ [22. pop](#22-pop)\n\t\t+ [23. push](#23-push)\n\t\t+ [24. reduce](#24-reduce)\n\t\t+ [26. reverse](#26-reverse)\n\t\t+ [27. shift](#27-shift)\n\t\t+ [28. slice](#28-slice)\n\t\t+ [29. some](#29-some)\n\t\t+ [30. sort](#30-sort)\n\t\t+ [31. splice](#31-splice)\n\t\t+ [34. toString](#34-tostring)\n\t\t+ [35. unshift](#35-unshift)\n\t\t+ [37. with](#37-with)\n\t\t+ [38. toSorted](#38-tosorted)\n\t\t+ [39. toReversed](#39-toreversed)\n\t\t+ [40. toSpliced](#40-tospliced)\n\t* [Array destructuring](#array-destructuring)\n\t* [Two-dimensional array](#two-dimensional-array)\n- [Conditinal statements](#conditinal-statements)\n\t* [Ternary operator](#ternary-operator)\n- [Function](#function)\n\t* [Regular / Named function](#regular--named-function)\n\t* [Function expression](#function-expression)\n\t* [Arrow function](#arrow-function)\n\t* [Immediately invoked function expression](#immediately-invoked-function-expression)\n\t* [Callback functions](#callback-functions)\n\t* [Default parameters](#default-parameters)\n\t* [bind method](#bind-method)\n- [Delay](#delay)\n\t* [Print \"Hello, World\" every 1 second](#print-hello-world-every-1-second)\n\t* [Print \"Hello, World\" after 1 second](#print-hello-world-after-1-second)\n- [Set](#set)\n- [Map](#map)\n- [Loops](#loops)\n\t* [for](#for)\n\t* [do...while](#dowhile)\n\t* [while](#while)\n\t* [break](#break)\n\t* [continue](#continue)\n\t* [labeled](#labeled)\n\t* [for...in](#forin)\n\t* [for...of](#forof)\n- [Falsy and Truthy values](#falsy-and-truthy-values)\n- [Logical AND (\u0026\u0026)](#logical-and-)\n- [Logical OR (||)](#logical-or-)\n- [JavaScript modules](#javascript-modules)\n- [Promises](#promises)\n\t* [Promise chaining](#promise-chaining)\n\t* [Promise.allSettled()](#promiseallsettled)\n- [Async \u0026 Await](#async--await)\n- [Constructor Functions](#constructor-functions)\n- [Prototype Inheritance](#prototype-inheritance)\n- [Class](#class)\n\t* [Subclass](#subclass)\n\t* [Getters and Setters](#getters-and-setters)\n- [Errors](#errors)\n\t* [Examples](#examples)\n- [Try Catch](#try-catch)\n- [Debugging](#debugging)\n\t* [Debugger](#debugger)\n\t* [Console](#console)\n\t* [Breakpoints](#breakpoints)\n- [HTML with live server](#html-with-live-server)\n- [How to add JavaScript to a web page](#how-to-add-javascript-to-a-web-page)\n\t* [Everything between script tags will be executed by the web browser](#everything-between-script-tags-will-be-executed-by-the-web-browser)\n\t* [Link an external file to a web page](#link-an-external-file-to-a-web-page)\n- [DOM - Document Object Model](#dom---document-object-model)\n\t* [DOM manipulation](#dom-manipulation)\n\t* [Event handling](#event-handling)\n\t\t+ [Event bubbling](#event-bubbling)\n\t\t+ [Event capturing](#event-capturing)\n- [Local Storage](#local-storage)\n- [Window interface](#window-interface)\n- [Strict mode](#strict-mode)\n- [HTTP requests](#http-requests)\n\t* [Callback pattern - Asynchronous execution](#callback-pattern---asynchronous-execution)\n\t* [Synchronous execution](#synchronous-execution)\n\t* [Fetch API](#fetch-api)\n- [Closure](#closure)\n- [Currying](#currying)\n- [Pure function](pure-function)\n- [Sleep](#sleep)\n- [Performance](#performance)\n- [Math](#math)\n- [Feature detection](#feature-detection)\n- [Resources](#resources)\n\n# History of JavaScript\n\nEcma (European Computer Manufacturers Association) International creates standardization of information and communication systems. You can find all the standards over [here](https://www.ecma-international.org/publications-and-standards/standards/). One of the standards is called [ecma-262](https://www.ecma-international.org/publications-and-standards/standards/ecma-262/). This refers to the specification for [ECMAScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Language_Resources) programming language.\n\nBelow we have a list of ECMAScript language specifications.\n\nES1 (1997), ES2 (1998), ES3 (1999), ES4, ES5 (2009), ES6 or ES2015 (2015), ES2016, ES2017, ES2018, ES2019, ES2020, ES2022\n\n[Brendan Eich](https://brendaneich.com/) created JavaScript at Netscape, and it was later revised to comply with ECMA-262 Edition 5 and subsequent versions. JavaScript can run on the client side (Chrome, Firefox, Microsoft Edge, Opera, Safari) and server-side (Node.js).\n\n[Ecma International, Technical Committee 39 - ECMAScript](https://github.com/tc39/proposals)\n\n# Introduction\n\nJavaScript is a prototype-based, single-threaded, dynamically-typed language.\n\n- [Call stack](https://developer.mozilla.org/en-US/docs/Glossary/Call_stack)\n- [Web APIs](https://developer.mozilla.org/en-US/docs/Web/API)\n- [Tasks](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide#tasks)\n- [Microtasks](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide#microtasks)\n- [Event loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Event_loop)\n\n# JavaScript runtimes\n\n| Runtime                             |\n|-------------------------------------|\n| [Node.js](https://nodejs.org/en)    |\n| [Deno](https://deno.com/)           |\n| [Bun](https://bun.sh/)              |\n\n# Reserved words\n\n```\nbreak, case, catch, class, const, continue, debugger, default, delete, do,\nelse, export, extends, false, finally, for, function, if, import, in,\ninstanceof, new, null, return, static, super, switch, this, throw, true,\ntry, typeof, var, void, while, with, yield\n```\n\n[Source](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#reserved_words)\n\n# Comments\n\n```js\n// single line comment\n```\n\n```js\n/*\nmultiline\ncomment\n*/\n```\n\n# Variables\n\nUse camel case for naming variables. Variable names can start with letters, `_` and `$` sign. It can't be reserved words.\n\n```js\nlet firstName = \"Bob\";\n```\n\n```js\nvar firstName = \"Bob\";\nlet id = 8765;\nconst BIRTH_DAY = \"1 Jan 2000\";\n```\n\nUse `let` and `var` if the value will change over time and `const` (can not be changed later, and you'll get an error if you try reassigning a new value) for a constant value. `var` has global and `let` has block scope. With `var` you can define same variables more than once. You can't define same `let` and `const` variables more than once.\n\n```js\nvar a = \"aaa\";\nvar a = \"aaa\";\n\nlet b = \"bbb\";\nlet b = \"bbb\"; // 'b' has already been declared\n\nconst C = \"ccc\";\nconst C = \"ccc\"; // 'C' has already been declared\n```\n\n## undefined and null\n\n**undefined:** It means a variable has been declared, but no value has not been assigned.\n\n```js\nlet name;\nconsole.log(name); // here undefined is the intial value for name\n```\n\nA function without a return statement will return a default value, in this case `undefined`.\n\n```js\nlet convertFahrenheitToCelsius = function (fahrenheit) {\n    console.log(fahrenheit); // undefined\n};\n\nconsole.log(convertFahrenheitToCelsius()); // undefined\n```\n\n**null:** null is set explicitly to describe nothing or void.\n\n```js\nlet name = null;\nconsole.log(name); // null\n```\n\n```js\nlet convertFahrenheitToCelsius = function (fahrenheit) {\n    console.log(fahrenheit); // undefined\n    return (fahrenheit - 32) * (5 / 9);\n};\n\nconsole.log(convertFahrenheitToCelsius()); // null\n```\n\n**undefined vs null:**\n\n```js\nconsole.log(undefined == null); // true\nconsole.log(undefined === null); // false\n```\n\n## Leaked variables\n\n```js\nif (true) {\n    age = 22;\n    console.log(age); // 22\n}\n```\n\n## Scope\n\nIn a scope variables can be accessed defined in that scope or defined in parent scope.\n\n```js\nlet fullName = \"Dariana Trahan\";\n\nif (true) {\n    let age = 22;\n    console.log(fullName); // parent scope\n    console.log(age); // local scope\n    if (true) {\n        let country = \"Australia\";\n        console.log(fullName); // parent scope\n        console.log(age); // parent scope\n        console.log(country); // local scope\n    }\n}\n\nif (true) {\n    let age = 22;\n    console.log(fullName); // parent scope\n    console.log(age); // local scope\n}\n\nif (true) {\n    let city = \"Melbourne\";\n    console.log(fullName); // parent scope\n    console.log(city); // local scope\n}\n```\n\nTree view of scopes.\n\n```\n                  fullName\n                 (fullName)\n             /       |       \\\n            /        |        \\\n         age        age        city\n(fullName, age) (fullName, age)  (fullName, city)\n         /\n    country\n(fullName, age, country)\n```\n\n### Global scope\n\nThe code is defined outside all code blocks.\n\n```js\nlet firstName = \"Dariana Trahan\"; // var name = \"Dariana Trahan\"; const name = \"Dariana Trahan\";\nconsole.log(firstName); // Dariana Trahan\n\nfunction getName() {\n    console.log(firstName); // Dariana Trahan\n}\n\nconsole.log(firstName); // Dariana Trahan\n```\n\n### Local scope\n\nThe code is defined inside a code block. Code in between two curly brackets `{}` is called a block.\n\n#### Function block\n\n```js\n// can't access it before the function\nconsole.log(firstName); // Uncaught ReferenceError: firstName is not defined\n```\n\n```js\nfunction getName() {\n    let firstName = \"Dariana Trahan\";\n    console.log(firstName);\n}\ngetName(); // Dariana Trahan\n```\n\n```js\n// can't access it after the function\nconsole.log(firstName); // Uncaught ReferenceError: firstName is not defined\n```\n\n#### if block\n\n```js\nif (true) {\n    let fullName = \"Dariana Trahan\"; // const fullName = \"Dariana Trahan\";\n    console.log(fullName); // Dariana Trahan\n}\n\nconsole.log(fullName); // Uncaught ReferenceError: fullName is not defined\n```\n\n#### Hoisting\n\nPrior to the execution of the code, the interpreter moves the definition of functions, variables, or classes to the top of their scope. This process is known as JavaScript hoisting. It does not take the value or initialization only declaration, `var`, `let`, `const` are hoisted, and only var declarations are initialized with `undefined`. On the other hand `let` and `const` declarations are not initialized.\n\n```js\nconsole.log(fullName); // ReferenceError: fullName is not defined\n\nif (true) {\n    let fullName = \"Dariana Trahan\";\n    console.log(fullName);\n}\n\nconsole.log(fullName);\n```\n\n```js\nconsole.log(fullName); // undefined\n\nif (true) {\n    var fullName = \"Dariana Trahan\";\n    console.log(fullName); // Dariana Trahan\n}\n\nconsole.log(fullName); // Dariana Trahan\n```\n\n```js\nif (true) {\n    var fullName;\n    console.log(fullName); // undefined\n}\n\nconsole.log(fullName); // undefined\nfullName = \"Dariana Trahan\";\n```\n\n```js\nfunction getFullName() {\n    var fullName = \"Dariana Trahan\";\n    console.log(fullName);\n}\n\nconsole.log(fullName); // ReferenceError: fullName is not defined\n```\n\n```js\nlet age = 20;\nif (age \u003e 30) {\n    var fullName = \"Dariana Trahan\";\n    console.log(fullName);\n}\n\nconsole.log(fullName); // undefined\n```\n\n\u003ctable\u003e\n\u003ctr\u003e\n\u003cth\u003eBefore Hoisting\u003c/th\u003e\n\u003cth\u003eAfter Hoisting\u003c/th\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003e\n\u003cpre lang=\"js\"\u003e\nconsole.log(fullName); // undefined\nfullName = \"Dariana Trahan\";\nconsole.log(fullName); // Dariana Trahan\nvar fullName;\n\u003c/pre\u003e\n\u003c/td\u003e\n\u003ctd\u003e\n\u003cpre lang=\"js\"\u003e\nvar fullName;\nconsole.log(fullName); // undefined\nfullName = \"Dariana Trahan\";\nconsole.log(fullName); // Dariana Trahan\n\u003c/pre\u003e\n\u003c/td\u003e\n\u003c/tr\u003e\n\u003c/table\u003e\n\n```js\nconsole.log(getFullName()); // Dariana Trahan\n\nfunction getFullName() {\n    return \"Dariana Trahan\";\n}\n```\n\nWe can avoid hoisting and save space using anonymous function expression.\n\n```js\nconsole.log(getFullName()); // Uncaught ReferenceError: getName is not defined\n\nconst getFullName = () =\u003e {\n    return \"Dariana Trahan\";\n};\n```\n\n# Data types\n\n| No  | Name      | Example                                                                                                        | Doc                                                                 | Data Type          |\n| --- | --------- | -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------ |\n| 1   | number    | `let a = 17`                                                                                                   | [link](https://developer.mozilla.org/en-US/docs/Glossary/Number)    | Primitive data     |\n| 2   | bigint    | `let a = 348378344239489n`                                                                                     | [link](https://developer.mozilla.org/en-US/docs/Glossary/BigInt)    | Primitive data     |\n| 3   | string    | `let a = \"Hello universe\"` \u003cbr/\u003e `let a = 'Hello universe'` \u003cbr/\u003e \u003ccode\u003e let a = \\`${Hello universe}\\` \u003c/code\u003e | [link](https://developer.mozilla.org/en-US/docs/Glossary/String)    | Primitive data     |\n| 4   | B=boolean   | `let a = true`                                                                                                 | [link](https://developer.mozilla.org/en-US/docs/Glossary/Boolean)   | Primitive data     |\n| 5   | symbol    | `let sym = Symbol()`                                                                                           | [link](https://developer.mozilla.org/en-US/docs/Glossary/Symbol)    | Primitive data     |\n| 6   | null      | `let a = null`                                                                                                 | [link](https://developer.mozilla.org/en-US/docs/Glossary/Null)      | Primitive data     |\n| 7   | undefined | `let a = undefined`                                                                                            | [link](https://developer.mozilla.org/en-US/docs/Glossary/undefined) | Primitive data     |\n| 8   | object    | `let a = {a: 'test'}`                                                                                          | [link](https://developer.mozilla.org/en-US/docs/Glossary/Object)    | Non-primitive data |\n\n## How to check the data type\n\n```js\ntypeof 17; // 'number'\ntypeof 348378344239489n; // 'bigint'\ntypeof \"Hello universe\"; // 'string'\ntypeof true; // 'boolean'\ntypeof Symbol(); // 'symbol'\ntypeof null; // 'object' -\u003e https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null\ntypeof undefined; // 'undefined'\ntypeof { a: \"test\" }; // 'object'\ntypeof [17, 18]; // 'object'\nArray.isArray([17, 18]); // true\nArray.isArray({ a: \"test\" }); // false\n```\n\n## Type coercion\n\n```js\n// String concatanation\nlet num1 = '2' + 3;\nconsole.log(num1); // 23\nconsole.log(typeof num1); // string\n\n// String concatanation\nlet num2 = 3 + '2';\nconsole.log(num2); // 32\nconsole.log(typeof num2); // string\n\n// Subtracting integers\nlet num3 = '3' - 2;\nconsole.log(num3); // 1\nconsole.log(typeof num3); // number\n\n// Subtracting integers\nlet num4 = 2 - '3';\nconsole.log(num4); // -1\nconsole.log(typeof num4); // number\n```\n\n```js\n// Check equality and type\nconsole.log(2 === 2); // true\nconsole.log('2' === 2); // false\n\n// Check equality without type\nconsole.log(2 == 2); // true\nconsole.log('2' == 2); // true\nconsole.log('3' == 2); // false\n```\n\n## string\n\nWe can use either single or double quotes for string values. The important thing is to start and end the string with the same type of quote.\n\n```js\nlet singleQuoteString = 'This is a string with single quotes.';\nlet doubleQuoteString = \"This is a string with double quotes.\";\n```\n\nAlthough string is a primitive data type, when we access methods and properties on a string it converts to an object, which is also true for a number and boolean. On the other hand `null` and `undefined` will never be an object.\n\n```js\nconst fullName = new String(\"Bob Rob\");\nconsole.log(fullName); // Bob Rob\n```\n\nBracket notation lets you access a string's character by its index, starting at 0 and ending at the string's length minus one.\n\n```js\nconst fullName = \"Bob Rob\";\nconst initialLetter = fullName[0];\nconsole.log(initialLetter); // B\n\n\nconst nthLetter = fullName[1]; // where n = 1\nconsole.log(nthLetter); // o\n\nconst lastLetter = fullName[fullName.length - 1];\nconsole.log(lastLetter); // b\n```\n\nIn JavaScript, once a string value is created, it cannot be changed. This property is known as immutability.\n\n```js\nlet fullName = \"Bob Rob\";\nfullName[0] = 'b';\nconsole.log(fullName); // Bob Rob\n```\n\nWe can reassign a new value\n\n```js\nlet fullName = \"Bob Rob\";\nfullName = \"bob Rob\";\nconsole.log(fullName); // bob Rob\n```\n\nParse string to number\n\n```js\n// parseInt(string)\nparseInt(\"10\"); // 10\n```\n\nParse binary string to decimal\n\n```js\n// parseInt(string, radix) here radix = An integer between 2 and 36\nparseInt(\"11\", 2); // 3\n```\n\n### Methods and properties\n\n```js\nlet fullName = \"Bob Rob\";\nconsole.log(fullName.length); // 7\nconsole.log(fullName.toUpperCase()); // BOB ROB\nconsole.log(fullName.toLowerCase()); // bob rob\nconsole.log(fullName.includes(\"bob\")); // false\nconsole.log(fullName.includes(\"Bob\")); // true\n\nlet sentence = \"ThereIsNoSpoon\";\nlet words = sentence.split(/(?=[A-Z])/);\nconsole.log(words); // ['There', 'Is', 'No', 'Spoon']\n```\n\n[Source](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)\n\n### Template strings\n\n```js\nlet name = \"Bob\";\nlet score = 10;\nlet result = `Name: ${name} - Score: ${score}`;\nconsole.log(result); // Name: Bob - Score: 10\n```\n\n### Escape charecters\n\nPlace a backslash (\\) before the quotes to point that they are not the end of the string.\n\n```js\nlet description = '\"If you\\'re going to do something, then do it properly.\"';\n```\n\n## number\n\nThe number data type can hold numbers between 2 \u003csup\u003e53-1\u003c/sup\u003e and -2 \u003csup\u003e53-1\u003c/sup\u003e.\n\nThe `Number.MAX_SAFE_INTEGER` constant represents 2 \u003csup\u003e53-1\u003c/sup\u003e and `Number.MIN_SAFE_INTEGER` constant represents -2 \u003csup\u003e53-1\u003c/sup\u003e.\n\n```js\nlet numInt = 710;\nlet numDec = 710.0;\nlet numExp = 7.1e2; // 7.1 * (10 ** 2)\nlet numOct = 0c1306;\nlet numHex = 0x2C6;\nlet numBin = 0b1011000110;\n```\n\n### Methods and properties\n\n```js\nlet num = 1220.4324345;\nconsole.log(num.toFixed(2)); // 1220.43\nconsole.log(Math.round(num)); // 1220\nconsole.log(Math.floor(num)); // 1220\nconsole.log(Math.ceil(num)); // 1221\n```\n\n[Source](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number)\n\n## bigint\n\ntodo\n\n## symbol\n\ntodo\n\n## undefind\n\ntodo\n\n## null\n\ntodo\n\n## object\n\n### Empty object.\n\n```js\nconst user = {};\n```\n\n### Equality\n\nPoints to two different memory locations.\n\n```js\nconsole.log({} === {}); // false\n```\n\nPoints to the same memory location.\n\n```js\nlet someObject = {};\nlet otherObject = someObject;\nconsole.log(someObject === otherObject); // true\n```\n\n### Object with properties and values.\n\n```js\nlet user = {\n    id: 1,\n    firstName: \"Bob\",\n    lastName: \"Rob\",\n    getFullName: function () {\n        console.log(this); // {id: 1, firstName: \"Bob\", lastName: \"Rob\", getFullName: ƒ()}\n        return `${this.firstName} ${this.lastName}`;\n    },\n};\n\nconsole.log(user); // {id: 1, firstName: \"Bob\", lastName: \"Rob\", getFullName: ƒ()}\nconsole.log(user.id); // 1\nconsole.log(user.firstName); // Bob\nconsole.log(user.lastName); // Rob\nconsole.log(user.getFullName()); // Bob Rob\n```\n\n### Object reference\n\n```js\nlet user = {\n    id: 1,\n    firstName: \"Bob\",\n    lastName: \"Rob\",\n    getFullName: function () {\n        return `${this.firstName} ${this.lastName}`;\n    },\n};\n\nlet changeId = function (u, newId) {\n    u.id = newId;\n    console.log(u);\n};\n\nconsole.log(user); // {id: 1, firstName: \"Bob\", lastName: \"Rob\", getFullName: ƒ()}\nchangeId(user, 10); // {id: 10, firstName: \"Bob\", lastName: \"Rob\", getFullName: ƒ()}\nconsole.log(user); // {id: 10, firstName: \"Bob\", lastName: \"Rob\", getFullName: ƒ()}\n```\n\n```js\nlet user = {\n    id: 1,\n    firstName: \"Bob\",\n    lastName: \"Rob\",\n    getFullName: function () {\n        return `${this.firstName} ${this.lastName}`;\n    },\n};\n\nlet changeId = function (u, newId) {\n    u = {};\n    u.id = newId;\n    console.log(u);\n};\n\nconsole.log(user); // {id: 1, firstName: \"Bob\", lastName: \"Rob\", getFullName: ƒ()}\nchangeId(user, 10); // {id: 10}\nconsole.log(user); // {id: 10, firstName: \"Bob\", lastName: \"Rob\", getFullName: ƒ()}\n```\n\n### Get all the keys.\n\n```js\nconst keys = Object.keys(user);\nconsole.log(keys); // ['id', 'firstName', 'lastName', 'getFullName']\n```\n\n### Get all the values.\n\n```js\nconst values = Object.values(user);\nconsole.log(values); // [1, 'bob', 'rob', ƒ]\n```\n\n### Checking properties.\n\nComing from `Object.prototype.hasOwnProperty()`\n\n```js\nconsole.log(user.hasOwnProperty(\"id\")); // true\nconsole.log(user.hasOwnProperty(\"age\")); // false\nconsole.log(user.hasOwnProperty(\"hasOwnProperty\")); // false\n```\n\n### Get all the keys and values.\n\n```js\nconst entries = Object.entries(user);\nconsole.log(entries);\n\n// 0: (2) ['id', 1]\n// 1: (2) ['firstName', 'bob']\n// 2: (2) ['lastName', 'rob']\n// 3: (2) ['getFullName', ƒ]\n```\n\n### Object destructuring\n\n```js\nlet user = {\n    id: 1,\n    firstName: \"bob\",\n    lastName: \"rob\",\n    address: {\n        unit: 2,\n        city: \"The City\",\n        country: \"The Country\",\n    },\n    getFullName: function () {\n        return `${this.firstName} ${this.lastName}`;\n    },\n};\n\nlet firstName = user.firstName;\n\nlet { firstName } = user;\n\nfunction userId(user) {\n    return user.id;\n}\n\nfunction userId({ id }) {\n    return id;\n}\n\nuserId(user);\n\n// Rename\n\nlet { firstName: fName } = user;\n// fName = 'bob'\n\nlet {\n    address: { unit, city, country },\n} = user;\n```\n\n### Object property shorthand\n\nWe can use the object property shorthand when the property value has the same name as the property key.\n\n```js\nlet user = {\n    id: id,\n    firstName: firstName,\n    lastName: lastName,\n};\n\nlet user = {\n    id,\n    firstName,\n    lastName,\n};\n```\n\n### Spread syntax (...)\n\n```js\nlet user = {\n    id: 1,\n    firstName: \"bob\",\n    lastName: \"rob\",\n    addresses: [\"56596 Yolanda Garden\", \"438 Cayla Island\", \"060 Christophe Flat\"]\n};\n\nfunction printUser(id, firstName, lastName, firstAddress, secondAddress) {\n    console.log(id); // 1\n    console.log(firstName); // bob\n    console.log(lastName); // rob\n    console.log(firstAddress); // 56596 Yolanda Garden\n    console.log(secondAddress); // 438 Cayla Island\n}\n\nprintUser(user.id, user.firstName, user.lastName, ...user.addresses);\n```\n\n```js\nlet addresses = [\"56596 Yolanda Garden\", \"438 Cayla Island\", \"060 Christophe Flat\"];\nlet newAddresses = [\"'897 Koby Square\", ...addresses];\nconsole.log(addresses); // [\"56596 Yolanda Garden\", \"438 Cayla Island\", \"060 Christophe Flat\"]\nconsole.log(newAddresses); // [\"'897 Koby Square\", \"56596 Yolanda Garden\", \"438 Cayla Island\", \"060 Christophe Flat\"]\n```\n\n### Rest syntax (parameters) (...)\n\nThe rest parameter syntax (last parameter in a function) allows a function to accept an indefinite number of arguments.\n\n```js\nlet user = {\n    id: 1,\n    firstName: \"bob\",\n    lastName: \"rob\",\n};\n\nfunction userId({ id, ...rest }) {\n    console.log(rest); // {firstName: 'bob', lastName: 'rob'}\n    return `${id} ${rest.firstName} ${rest.lastName}`;\n}\n\nuserId(user); // '1 bob rob'\n```\n\n### object Spread syntax\n\nHere order matters. Whatever comes last will take precedence.\n\n```js\nlet user = {\n    id: 1,\n    firstName: \"bob\",\n    lastName: \"rob\",\n};\n\nfunction userId({...rest}) {\n    return {\n        id: 40,\n        ...rest,\n        id: rest.id + 1\n    };\n}\n\nconsole.log(userId(user)); // {id: 2, firstName: 'bob', lastName: 'rob'}\n```\n\n### Delete properties\n\n```js\nlet user = {\n    id: 1,\n    firstName: \"bob\",\n    lastName: \"rob\",\n};\n\nconsole.log(user); // {id: 1, firstName: 'bob', lastName: 'rob'}\ndelete user.id;\nconsole.log(user); // {firstName: 'bob', lastName: 'rob'}\n```\n\n### Group by\n\n\n```js\nconst data = [\n  {\"name\": \"Carter, Smith and Tanner\", \"category\": \"Finance\", \"price\": 288.63},\n  {\"name\": \"Porter Inc\", \"category\": \"Healthcare\", \"price\": 117.84},\n  {\"name\": \"Liu, Collins and Martinez\", \"category\": \"Finance\", \"price\": 332.91},\n  {\"name\": \"Mcmahon-White\", \"category\": \"Technology\", \"price\": 490.14},\n  {\"name\": \"Goodman, Rosario and Wilcox\", \"category\": \"Finance\", \"price\": 66.88},\n  {\"name\": \"Anderson Inc\", \"category\": \"Finance\", \"price\": 389.29},\n  {\"name\": \"Bright Group\", \"category\": \"Healthcare\", \"price\": 149.5},\n  {\"name\": \"Brown Inc\", \"category\": \"Entertainment\", \"price\": 276.45},\n  {\"name\": \"Patton, Edwards and Rodriguez\", \"category\": \"Entertainment\", \"price\": 107.06},\n  {\"name\": \"Parker, Lam and Gonzalez\", \"category\": \"Education\", \"price\": 351.79}\n]\n\nconst result = Object.groupBy(data, ({ category }) =\u003e category);\n\n/*\n{\n\t\"Finance\": [{\n\t\t\"name\": \"Carter, Smith and Tanner\",\n\t\t\"category\": \"Finance\",\n\t\t\"price\": 288.63\n\t}, {\n\t\t\"name\": \"Liu, Collins and Martinez\",\n\t\t\"category\": \"Finance\",\n\t\t\"price\": 332.91\n\t}, {\n\t\t\"name\": \"Goodman, Rosario and Wilcox\",\n\t\t\"category\": \"Finance\",\n\t\t\"price\": 66.88\n\t}, {\n\t\t\"name\": \"Anderson Inc\",\n\t\t\"category\": \"Finance\",\n\t\t\"price\": 389.29\n\t}],\n\t\"Healthcare\": [{\n\t\t\"name\": \"Porter Inc\",\n\t\t\"category\": \"Healthcare\",\n\t\t\"price\": 117.84\n\t}, {\n\t\t\"name\": \"Bright Group\",\n\t\t\"category\": \"Healthcare\",\n\t\t\"price\": 149.5\n\t}],\n\t\"Technology\": [{\n\t\t\"name\": \"Mcmahon-White\",\n\t\t\"category\": \"Technology\",\n\t\t\"price\": 490.14\n\t}],\n\t\"Entertainment\": [{\n\t\t\"name\": \"Brown Inc\",\n\t\t\"category\": \"Entertainment\",\n\t\t\"price\": 276.45\n\t}, {\n\t\t\"name\": \"Patton, Edwards and Rodriguez\",\n\t\t\"category\": \"Entertainment\",\n\t\t\"price\": 107.06\n\t}],\n\t\"Education\": [{\n\t\t\"name\": \"Parker, Lam and Gonzalez\",\n\t\t\"category\": \"Education\",\n\t\t\"price\": 351.79\n\t}]\n}\n*/\n```\n\n# Array\n\n```js\nconst arr1 = Array(1, 2, 3, 4, 5, 6, 7, 8, 9);\nconst arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];\n\nconsole.log(arr1[4]);\nconsole.log(arr2[4]);\n```\n\nA 2D array, also known as a two-dimensional array, consists of an array containing other arrays.\n\n```js\nconst arr3 = [\n  [1, 2, 3],\n  [4, 5, 6],\n  [7, 8, 9]\n];\n\nconsole.log(arr3[1][1]);\n```\n\n## Array methods\n\n| No  | Name             | When to use |\n| --- | ---------------- | ----------- |\n| 1   | at()             |             |\n| 2   | concat()         |             |\n| 3   | copyWithin()     |             |\n| 4   | entries()        |             |\n| 5   | every()          |             |\n| 6   | fill()           |             |\n| 7   | filter()         |             |\n| 8   | findIndex()      |             |\n| 9   | find()           |             |\n| 10  | flat()           |             |\n| 11  | flatMap()        |             |\n| 12  | forEach()        |             |\n| 13  | from()           |             |\n| 14  | includes()       |             |\n| 15  | indexOf()        |             |\n| 16  | isArray()        |             |\n| 17  | join()           |             |\n| 18  | keys()           |             |\n| 19  | lastIndexOf()    |             |\n| 20  | map()            |             |\n| 21  | of()             |             |\n| 22  | pop()            |             |\n| 23  | push()           |             |\n| 24  | reduce()         |             |\n| 25  | reduceRight()    |             |\n| 26  | reverse()        |             |\n| 27  | shift()          |             |\n| 28  | slice()          |             |\n| 29  | some()           |             |\n| 30  | sort()           |             |\n| 31  | splice()         |             |\n| 32  | toLocaleString() |             |\n| 33  | toSource()       |             |\n| 34  | toString()       |             |\n| 35  | unshift()        |             |\n| 36  | values()         |             |\n| 37  | with()           |             |\n| 38  | toSorted()       |             |\n| 39  | toReveresed()    |             |\n| 40  | toSpliced()      |             |\n\n### 1. at\n\n### 2. concat\n\n```js\nconst arr1 = [1, 2, 3];\nconst arr2 = [1, 4, 5];\nconst arr3 = arr1.concat(arr2);\nconsole.log(arr3); // [1, 2, 3, 1, 4, 5]\n// or\nconst arr3 = [...arr1, ...arr2];\nconsole.log(arr3); // [1, 2, 3, 1, 4, 5]\n```\n\n### 5. every\n\n```js\nlet fruits = [\"Apple\", \"Banana\", \"Orange\", \"Mango\", \"Apple\"];\nlet every = fruits.every((fruit) =\u003e fruit.toLowerCase().includes(\"apple\"));\nconsole.log(fruits + \"/\" + every); // Apple,Banana,Orange,Mango/false\n\nlet fruits = [\"Apple\", \"Apple\", \"Apple\", \"Apple\", \"Apple\"];\nlet every = fruits.every((fruit) =\u003e fruit.toLowerCase().includes(\"apple\"));\nconsole.log(fruits + \"/\" + every); // Apple,Apple,Apple,Apple,Apple/true\n```\n\n### 6. fill\n\n```js\nconst arr = Array(10).fill(0);\nconsole.log(arr); // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n```\n\n### 7. filter\n\n```js\nlet fruits = [\"Apple\", \"Banana\", \"Orange\", \"Mango\", \"Apple\"];\nlet filter = fruits.filter((fruit) =\u003e fruit.toLowerCase().includes(\"apple\"));\nconsole.log(fruits + \"/\" + filter); // Apple,Banana,Orange,Mango/Apple,Apple\n```\n\n```js\nlet notes = [\n    {\n        title: \"First title\",\n        body: \"First body\",\n    },\n    {\n        title: \"Second title\",\n        body: \"Second body\",\n    },\n    {\n        title: \"Third title\",\n        body: \"Third body\",\n    },\n];\n\nlet filterdNotes = notes.filter((note, index) =\u003e {\n    const isTitleMatch = note.title.toLowerCase().includes(\"rs\");\n    const isBodyMatch = note.body.toLowerCase().includes(\"rs\");\n    return isTitleMatch || isBodyMatch;\n});\n\nconsole.log(JSON.stringify(filterdNotes)); // [{\"title\":\"First title\",\"body\":\"First body\"}]\n```\n\n### 8. findIndex\n\n```js\nlet fruits = [\"Apple\", \"Banana\", \"Orange\", \"Mango\", \"Apple\"];\nlet index = fruits.findIndex((fruit) =\u003e {\n    return fruit.toLowerCase().includes(\"apple\");\n});\nconsole.log(fruits + \"/\" + index); // Apple,Banana,Orange,Mango/0\n```\n\n```js\nlet notes = [\n    {\n        title: \"First title\",\n        body: \"First body\",\n    },\n    {\n        title: \"Second title\",\n        body: \"Second body\",\n    },\n    {\n        title: \"Third title\",\n        body: \"Third body\",\n    },\n];\n\nlet index = notes.findIndex((note, index) =\u003e {\n    return note.title === \"Second title\";\n});\n\nconsole.log(JSON.stringify(notes) + \"/\" + index); // [{\"title\":\"First title\",\"body\":\"First body\"},{\"title\":\"Second title\",\"body\":\"Second body\"},{\"title\":\"Third title\",\"body\":\"Third body\"}]/1\n```\n\n```js\nlet notes = [\n    {\n        title: \"First title\",\n        body: \"First body\",\n    },\n    {\n        title: \"Second title\",\n        body: \"Second body\",\n    },\n    {\n        title: \"Third title\",\n        body: \"Third body\",\n    },\n];\n\nconst findNote = (notes, title) =\u003e {\n    let index = notes.findIndex((note, index) =\u003e {\n        return note.title.toLowerCase() === title.toLowerCase();\n    });\n    return notes[index];\n};\n\nlet note = findNote(notes, \"second title\");\nconsole.log(note); // {title: \"Second title\", body: \"Second body\"}\n```\n\n### 9. find\n\nReturn the first occurrence of an item.\n\n```js\nlet fruits = [\"Apple\", \"Banana\", \"Orange\", \"Mango\", \"Apple\"];\nlet find = fruits.find((fruit) =\u003e fruit.toLowerCase().includes(\"apple\"));\nconsole.log(fruits + \"/\" + find); // Apple,Banana,Orange,Mango/Apple\n```\n\n```js\nlet notes = [\n    {\n        title: \"First title\",\n        body: \"First body\",\n    },\n    {\n        title: \"Second title\",\n        body: \"Second body\",\n    },\n    {\n        title: \"Third title\",\n        body: \"Third body\",\n    },\n];\n\nconst findNote = (notes, title) =\u003e {\n    return notes.find((note, index) =\u003e {\n        return note.title.toLowerCase() === title.toLowerCase();\n    });\n};\n\nlet note = findNote(notes, \"second title\");\nconsole.log(note); // {title: \"Second title\", body: \"Second body\"}\n```\n\n### 12. forEach\n\n`forEach` function takes single argument (a function or a callback function), and this function gets called with some arguments.\n\n```js\nforEach((element) =\u003e {\n    /* … */\n});\nforEach((element, index) =\u003e {\n    /* … */\n});\nforEach((element, index, array) =\u003e {\n    /* … */\n});\n// element = The current element being processed in the array.\n// index = The index of element in the array.\n// array = The array forEach() was called upon.\n```\n\n```js\nlet names = [\n    \"Dariana Trahan\",\n    \"Lillie Earl\",\n    \"Esther Yeager\",\n    \"Marianna Brownlee\",\n    \"Sara Tong\",\n    \"Clint Winslow\",\n    \"Efrain Popp\",\n    \"Anya Aiello\",\n    \"Sergio Truitt\",\n    \"Keyshawn Apodaca\",\n];\n\nnames.forEach((name) =\u003e console.log(name));\n\n/*\nDariana Trahan\nLillie Earl\nEsther Yeager\nMarianna Brownlee\nSara Tong\nClint Winslow\nEfrain Popp\nAnya Aiello\nSergio Truitt\nKeyshawn Apodaca\n*/\n```\n\n```js\nnames.forEach((name, index) =\u003e console.log(index, \":\", name));\n\n/*\n0,\":\",\"Dariana Trahan\"\n1,\":\",\"Lillie Earl\"\n2,\":\",\"Esther Yeager\"\n3,\":\",\"Marianna Brownlee\"\n4,\":\",\"Sara Tong\"\n5,\":\",\"Clint Winslow\"\n6,\":\",\"Efrain Popp\"\n7,\":\",\"Anya Aiello\"\n8,\":\",\"Sergio Truitt\"\n9,\":\",\"Keyshawn Apodaca\"\n*/\n```\n\n```js\nnames.forEach((name, index, array) =\u003e\n    console.log(index, \":\", name, \"-\", array[index])\n);\n\n/*\n0,\":\",\"Dariana Trahan\",\"-\",\"Dariana Trahan\"\n1,\":\",\"Lillie Earl\",\"-\",\"Lillie Earl\"\n2,\":\",\"Esther Yeager\",\"-\",\"Esther Yeager\"\n3,\":\",\"Marianna Brownlee\",\"-\",\"Marianna Brownlee\"\n4,\":\",\"Sara Tong\",\"-\",\"Sara Tong\"\n5,\":\",\"Clint Winslow\",\"-\",\"Clint Winslow\"\n6,\":\",\"Efrain Popp\",\"-\",\"Efrain Popp\"\n7,\":\",\"Anya Aiello\",\"-\",\"Anya Aiello\"\n8,\":\",\"Sergio Truitt\",\"-\",\"Sergio Truitt\"\n9,\":\",\"Keyshawn Apodaca\",\"-\",\"Keyshawn Apodaca\"\n*/\n```\n\n### 14. includes\n\n```js\nlet arr = [1, 1, 23, , 5];\n\nconsole.log(arr.includes(1)); // true\nconsole.log(arr.includes(6)); // false\nconsole.log(arr.includes(5)); // true\n```\n\n### 15. indexOf\n\n```js\nlet arr = [1, 1, 23, , 5];\n\nconsole.log(arr.indexOf(1)); // 0\nconsole.log(arr.indexOf(6)); // -1\nconsole.log(arr.indexOf(5)); // 4\n```\n\n### 17. join\n\n```js\nconst words = [\"There\", \"Is\", \"No\", \"Spoon\"];\nconsole.log(words.join(\", \")); // There, Is, No, Spoon\n```\n\n### 19. lastIndexOf\n\n```js\nconsole.log(arr3.lastIndexOf(1)); // 3\n```\n\n### 20. map\n\n```js\nlet letters = [\"a\", \"b\", \"c\"];\nlet upperCaseLetters = letters.map((letter) =\u003e letter.toUpperCase());\nconsole.log(letters + \"/\" + upperCaseLetters); // a,b,c/A,B,C\n```\n\n### 22. pop\n\n```js\n// Remove an item from the end\nlet num = [1, 2, 3, 1, 4, 5, 1234];\nlet rmItem = num.pop();\nconsole.log(num); // [1, 2, 3, 1, 4, 5]\nconsole.log(rmItem); // 1234\n```\n\n### 23. push\n\n```js\n// Add an item at the end\nlet num = [1, 2, 3, 1, 4, 5];\nnum.push(1234);\nconsole.log(num); // [1, 2, 3, 1, 4, 5, 1234]\n```\n\n### 24. reduce\n\n```js\nlet num = [1, 2, 5666, 22, 45, 7, 0];\nconst sum = num.reduce((acc, cur) =\u003e acc + cur);\nconsole.log(num + \"/\" + sum); // 1,2,5666,22,45,7,0/5743\n\nlet letters = [\"a\", \"b\", \"c\"];\nconst join = letters.reduce((acc, cur) =\u003e acc + cur);\nconsole.log(letters + \"/\" + join); // a,b,c/abc\n```\n\n### 26. reverse\n\n```js\nlet num = [1, 2, 5666, 22, 45, 7, 0];\nnum.reverse();\nconsole.log(num); // [0, 7, 45, 22, 5666, 2, 1]\n```\n\n### 27. shift\n\n```js\n// Remove an item at the beginning and shift rest of the elements to the left\nlet num = [1234, 1, 2, 3, 1, 4, 5];\nlet rmItem = num.shift();\nconsole.log(num); // [1, 2, 3, 1, 4, 5]\nconsole.log(rmItem); // 1234\n```\n\n### 28. slice\n\nThe slice(start, end) method where the end is exclusive returns a shallow copy of a part of an array and returns a new array. It does not change the original array.\n\n```js\nlet num = [1, 2, 3, 1, 4, 5];\n// [1, 2, 3, 1, 4, 5]\n//           ^\nconsole.log(num.slice(3, 4)); // [1]\n\nconsole.log(num); // [1, 2, 3, 1, 4, 5]\n\n// other variations\n// [1, 2, 3, 1, 4, 5]\n//  ^  ^  ^  ^  ^  ^\nconsole.log(num.slice()); // [1, 2, 3, 1, 4, 5]\n// [1, 2, 3, 1, 4, 5]\n//           ^  ^  ^\nconsole.log(num.slice(3)); // [1, 4, 5]\n```\n\n### 29. some\n\n```js\nlet fruits = [\"Apple\", \"Banana\", \"Orange\", \"Mango\", \"Apple\"];\nlet some = fruits.some((fruit) =\u003e fruit.toLowerCase().includes(\"apple\"));\nconsole.log(fruits + \"/\" + some); // Apple,Banana,Orange,Mango/true\n```\n\n### 30. sort\n\n```js\nlet nums = [1, 2, 5666, 22, 45, 7, 0];\nnums.sort();\nconsole.log(nums); // [0, 1, 2, 22, 45, 5666, 7]\n```\n\n```js\nlet notes = [\n    {\n        title: \"Second title\",\n        body: \"Second body\",\n    },\n    {\n        title: \"Third title\",\n        body: \"Third body\",\n    },\n    {\n        title: \"First title\",\n        body: \"First body\",\n    },\n];\n\nconst sortNotes = (notes) =\u003e {\n    return notes.sort((a, b) =\u003e {\n        if (a.title.toLowerCase() \u003c b.title.toLowerCase()) {\n            return -1;\n        } else if (b.title.toLowerCase() \u003c b.title.toLowerCase()) {\n            return 1;\n        } else {\n            return 0;\n        }\n    });\n};\n\nsortNotes(notes);\nconsole.log(notes); // [{title: \"First title\", body: \"First body\"}, {title: \"Second title\", body: \"Second body\"}, {title: \"Third title\", body: \"Third body\"}]\n```\n\n### 31. splice\n\nThe splice(start, deleteCount, item1, item2, itemN) returns an array containing the deleted element. It modifies the original array by removing or adding additional items.\n\n```js\nlet num = [1, 2, 3, 1, 4, 5];\n// [1, 2, 3, 1, 4, 5]\n//     ^  ^  ^  ^\nlet delItems = num.splice(1, 4, 20, 21, 22, 23);\nconsole.log(delItems); // [2, 3, 1, 4]\nconsole.log(num); // [1, 20, 21, 22, 23, 5]\n\n// other variations\nlet num = [1, 2, 3, 1, 4, 5];\n// [1, 2, 3, 1, 4, 5]\n//        ^  ^  ^  ^\nconsole.log(num.splice(2)); // [3, 1, 4, 5]\nconsole.log(num); // [1, 2]\n\nlet num = [1, 2, 3, 1, 4, 5];\n// [1, 2, 3, 1, 4, 5]\n//     ^\nconsole.log(num.splice(1, 1)); // [2]\nconsole.log(num); // [1, 3, 1, 4, 5]\n\nlet num = [1, 2, 3, 1, 4, 5];\n// [1, 2, 3, 1, 4, 5]\n//  ^  ^\nconsole.log(num.splice(0, 2, 4566)); // [1, 2]\nconsole.log(num); // [4566, 3, 1, 4, 5]\n\nlet num = [1, 3, 4];\n// [1, 3, 4]\n//     \u003c- insert here\nconsole.log(num.splice(1, 0, 2)); // []\nconsole.log(num); // [1, 2, 3, 4]\n```\n\n### 34. toString\n\n```js\nconsole.log(arr3.toString()); // 1,2,3,1,4,5\n```\n\n### 35. unshift\n\n```js\n// Add an item at the beginning and shift rest of the elements to the right\nlet num = [1, 2, 3, 1, 4, 5];\nnum.unshift(1234);\nconsole.log(num); // [1234, 1, 2, 3, 1, 4, 5]\n```\n\n### 37. with\n\n```js\nlet num = [1, 2, 3, 1, 4, 5];\nlet newNum = num.with(0, 8);\nconsole.log(\"num\", num); // [1, 2, 3, 1, 4, 5]\nconsole.log(\"newNum\", newNum); // [8, 2, 3, 1, 4, 5]\n```\n\n### 38. toSorted\n\nDoes not mutate the original array.\n\n```js\nlet num = [1, 2, 3, 1, 4, 5];\nlet newNum = num.toSorted();\nconsole.log(\"num\", num); // [1, 2, 3, 1, 4, 5]\nconsole.log(\"newNum\", newNum); // [1, 1, 2, 3, 4, 5]\n```\n\n### 39. toReversed\n\nDoes not mutate the original array.\n\n\n```js\nlet num = [1, 2, 3, 1, 4, 5];\nlet newNum = num.toReversed();\nconsole.log(\"num\", num); // [1, 2, 3, 1, 4, 5]\nconsole.log(\"newNum\", newNum); // [5, 4, 1, 3, 2, 1]\n```\n\n### 40. toSpliced\n\nDoes not mutate the original array.\n\n```js\nlet num = [1, 2, 3, 1, 4, 5];\nlet newNum = num.toSpliced(0, 3);\nconsole.log(\"num\", num); // [1, 2, 3, 1, 4, 5]\nconsole.log(\"newNum\", newNum); // [1, 4, 5]\n```\n\n## Array destructuring\n\n```js\nlet num = [123, 44, 65];\nlet [first, second] = num;\n\n/*\nfunction firstNum(num) {\n    return num[0];\n}\n*/\n\nfunction firstNum([first]) {\n    return first;\n}\n\nfirstNum(num);\n\n// Skip\nlet [first, , third] = num;\n\n// Rest of the array\nlet [first, ...others] = num;\n// others = [44, 65]\n\n// Skip and rest of the array\nlet [first, , ...others] = num;\n// others = [65]\n\nlet nums = [\n    [1, 2, 3],\n    [4, 5, 6],\n];\n\nlet [row1, row2] = nums;\nconsole.log(row1 + \" \" + row2);\n\nfor (const [first, second, third] of nums) {\n    console.log(first, second, third);\n}\n```\n\n## Two-dimensional array\n\n```js\nlet nums = [\n    [1, 2, 3],\n    [4, 5, 6],\n];\n\nconsole.log(nums[0]); // [1, 2, 3]\nconsole.log(nums[1]); // [4, 5, 6]\nconsole.log(nums[0][1]); // 2\n```\n\n[Source](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)\n\n# Conditinal statements\n\n```js\nlet num = 89;\n\nif (num === 89) {\n    console.log(\"89\");\n} else if (num === 90) {\n    console.log(\"90\");\n} else {\n    console.log(\"Not 89 or 90\");\n}\n```\n\n```js\nlet num = 89;\n\nswitch (num) {\n    case 89:\n        console.log(\"89\");\n        break;\n    case 90:\n        console.log(\"90\");\n        break;\n    default:\n        console.log(\"Not 89 or 90\");\n}\n```\n\n```js\nlet num = 89;\n\nlet is89 = num === 89 ? true : false;\nconsole.log(is89);\n```\n\n## Ternary operator\n\n```js\nconst age = 22;\nlet message = age \u003e= 18 ? \"You're over 18\" : \"You're under 18\";\nconsole.log(message); // You're over 18\n```\n\n# Function\n\n-   Regular / Named function\n-   Function expression / Anonymous function\n-   Arrow function\n-   Immediately invoked function expression\n-   Callback functions\n\n## Regular / Named function\n\nYou can use functions before you create them because they are hoisted.\n\n```js\nfunction hello() {\n    return \"hello world\";\n}\n\nhello(); // 'hello world'\n```\n\n```js\nfunction hello(name) {\n    return name;\n}\n\nhello(\"hello world\"); // 'hello world'\n```\n\nThe `arguments` object (local variable) accessible inside functions that contains the values of the arguments passed to that function. It is available within all non-arrow functions.\n\n```js\nfunction hello() {\n    console.log(arguments); // {0: \"1\", 1: \"2\", 2: \"3\"}\n    return \"hello world\";\n}\n\nhello(\"1\", \"2\", \"3\")\n```\n\n```js\nlet user = {\n    id: 1,\n    firstName: \"Bob\",\n    lastName: \"Rob\",\n    getFullName: function () {\n        console.log(this); // {id: 1, firstName: \"Bob\", lastName: \"Rob\", getFullName: ƒ()}\n        return `${this.firstName} ${this.lastName}`;\n    },\n};\n\nconsole.log(user.getFullName());\n```\n\n```js\nlet user = {\n    id: 1,\n    firstName: \"Bob\",\n    lastName: \"Rob\",\n    getFullName() {\n        console.log(this); // {id: 1, firstName: \"Bob\", lastName: \"Rob\", getFullName: ƒ()}\n        return `${this.firstName} ${this.lastName}`;\n    },\n};\n\nconsole.log(user.getFullName());\n```\n\n[Source](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments)\n\n## Function expression\n\nYou can't use function expressions before you create them. So they are not hoisted.\n\n```js\nconst hello = function () {\n    return \"hello world\";\n};\n\nhello(); // 'hello world'\n```\n\n## Arrow function\n\nWith block body, we need explicit return.\n\n```js\nconst hello = () =\u003e {\n    return \"hello world\";\n};\n\nhello(); // 'hello world'\n```\n\nWith a concise body, we can have an implicit return using the shorthand syntax.\n\n```js\nconst hello = () =\u003e \"hello world\";\n\nhello(); // 'hello world'\n```\n\nArrow functions don't have `this` and `arguments` binding.\n\n```js\nconst hello = () =\u003e {\n    console.log(arguments); // Uncaught ReferenceError: arguments is not defined\n    return \"hello world\";\n}\n\nhello(\"1\", \"2\", \"3\")\n```\n\n```js\nlet user = {\n    id: 1,\n    firstName: \"Bob\",\n    lastName: \"Rob\",\n    getFullName: () =\u003e {\n        console.log(this); // undefined\n        return `${this.firstName} ${this.lastName}`; // TypeError: Cannot read properties of undefined (reading 'firstName')\n    },\n};\n\nconsole.log(user.getFullName());\n```\n\n## Immediately invoked function expression\n\n```js\n(function () {\n    return \"hello world\";\n})();\n\n(() =\u003e {\n    return \"hello world\";\n})();\n\n(async () =\u003e {\n    return \"hello world\";\n})();\n```\n\nStore the return value.\n\n```js\nlet result = (function () {\n    return \"hello world\";\n})();\nconsole.log(result); // hello world\n```\n\n## Callback functions\n\nA callback function (A) is a function passed into another function (B) as an argument, which can be called by that function (B).\n\nHere function `hello` will call the function `B` at some point.\n\n```js\n// A\nconst callBackThisFunction = (name) =\u003e {\n    return \"Hello, \" + name;\n};\n\n// B\nconst hello = (callback, name) =\u003e {\n    return callback(name);\n};\n\nconsole.log(hello(callBackThisFunction, \"Bob\"));\n```\n\nAlos can be written as:\n\n```js\nconst hello = (callback, name) =\u003e {\n    return callback(name);\n};\n\nconsole.log(hello((name) =\u003e {\n    return \"Hello, \" + name;\n}, \"Bob\"));\n```\n\n## Default parameters\n\n```js\nlet getResult = function (name = \"Anonymous\", score = 0) {\n    return `Name: ${name} - Score: ${score}`;\n};\n\nconsole.log(getResult());\n```\n\n## bind method\n\nWe can create a new function using the bind() method and it takes the value for `this` keyword as an argument.\n\n```js\nlet person = {\n    firstName: \"Bob\",\n    lastName: \"Rob\",\n    fullName: function (type) {\n        return `${type}: ${this.firstName} ${this.lastName}`\n    }\n}\n\nconsole.log(person.fullName('Person')); // Person: Bob Rob\n\nlet student = {\n    firstName: \"Tom\",\n    lastName: \"Jon\",\n}\n\n\nlet teacher = {\n    firstName: \"Ron\",\n    lastName: \"Von\",\n}\n\nlet studentFullName = person.fullName.bind(student, 'Student');\nconsole.log(studentFullName()); // Student: Tom Jon\n\nlet teacherFullName = person.fullName.bind(teacher, 'Teacher');\nconsole.log(teacherFullName()); // Teacher: Ron Von\n```\n\n# Delay\n\n## Print \"Hello, World\" every 1 second\n\n```js\nconst callBackThisFunction = (name) =\u003e {\n    console.log(\"Hello, World\");\n};\n\nsetInterval(callBackThisFunction, 1000);\n```\n\n## Print \"Hello, World\" after 1 second\n\n```js\nconst callBackThisFunction = (name) =\u003e {\n    console.log(\"Hello, World\");\n};\n\nsetTimeout(callBackThisFunction, 1000);\n```\n\n# Set\n\n```js\nconst numbers = new Set([1, 2, 3]);\n```\n\n# Map\n\n```js\nconst digtiMap = new Map([\n  [1, \"one\"],\n  [2, \"two\"],\n  [3, \"three\"],\n]);\n```\n\n# Loops\n\n## for\n\n```js\nfor ([initialExpression]; [conditionExpression]; [incrementExpression])\n    statement;\n\nfor (let num = 1; num \u003c= 10; num++) {\n    console.log(\"#\", num);\n}\n```\n\n## do...while\n\n```js\n// do...while can be useful when you want to execute the statement at least once\n\ndo statement;\nwhile (condition);\n\nlet num = 1;\ndo {\n    console.log(\"#\", num);\n    num += 1;\n} while (num \u003c= 10);\n```\n\n## while\n\n```js\nwhile (condition) statement;\n\nlet num = 1;\nwhile (num \u003c= 10) {\n    console.log(\"#\", num);\n    num += 1;\n}\n```\n\n## break\n\n```js\n// break without a label terminates the innermost enclosing while, do-while, for, or switch immediately and transfers control to the following statement\n\nbreak;\nbreak label;\n\nlet theNum = 5;\nfor (let num = 1; num \u003c= 10; num++) {\n    if (num === theNum) {\n        console.log('Found the number', theNum);\n        break;\n    }\n    console.log('Looking at', num);\n}\n\n// The following code will break the inner loop 10 times and print \"Found the number 5\" 10 times\nlet theNum = 5;\nfor (let outer = 1; outer \u003c= 10; outer++) {\n    for (let inner = 1; inner \u003c= 10; inner++) {\n        if (inner === theNum) {\n            console.log('Found the number', theNum);\n            break;\n        }\n        console.log('Looking at', inner);\n    }\n}\n\n\n// The following code will break the inner and outer loop and print \"Found the number 5\" once.\nlet theNum = 5;\nouterLoop:\nfor (let outer = 1; outer \u003c= 10; outer++) {\n    innerLoop:\n    for (let inner = 1; inner \u003c= 10; inner++) {\n        if (inner === theNum) {\n            console.log('Found the number', theNum);\n            break outerLoop;\n        }\n        console.log('Looking at', inner);\n    }\n}\n```\n\n## continue\n\n```js\n// continue without a label terminates the innermost enclosing while, do-while, for, or switch immediately and continues execution of the loop with the next iteration.\n\ncontinue;\ncontinue label;\n\n// Look at all the numbers.\nlet theNum = 5;\nfor (let num = 1; num \u003c= 10; num++) {\n    if (num === theNum) {\n        console.log('Found the number', theNum);\n        continue;\n    }\n    console.log('Looking at', num);\n}\n\n\n// todo\n```\n\n## labeled\n\n```js\n// labeled statement is used with a break or continue statements.\n\nlabel: statement;\n\n// todo\n```\n\n## for...in\n\n`for...in` statement iterates over object literals to get the index/keys of the object.\n\n```js\nfor (variable in object) statement;\n\nlet names = [\n    \"Dariana Trahan\",\n    \"Lillie Earl\",\n    \"Esther Yeager\",\n    \"Marianna Brownlee\",\n    \"Sara Tong\",\n    \"Clint Winslow\",\n    \"Efrain Popp\",\n    \"Anya Aiello\",\n    \"Sergio Truitt\",\n    \"Keyshawn Apodaca\",\n];\n\nfor (const i in names) {\n    console.log(names[i]);\n}\n\nlet person = {\n    name: \"Dariana Trahan\",\n    age: 21,\n    address: \"localhost\",\n};\n\nfor (const key in person) {\n    console.log(key, \":\", person[key]);\n}\n```\n\n## for...of\n\n`for...of` statement iterates over iterable objects including String, Array, TypedArray, Map, Set, and Intl. Segments to get the property values.\n\n```js\nfor (variable of object) statement;\n\nlet names = [\n    \"Dariana Trahan\",\n    \"Lillie Earl\",\n    \"Esther Yeager\",\n    \"Marianna Brownlee\",\n    \"Sara Tong\",\n    \"Clint Winslow\",\n    \"Efrain Popp\",\n    \"Anya Aiello\",\n    \"Sergio Truitt\",\n    \"Keyshawn Apodaca\",\n];\n\nfor (const name of names) {\n    console.log(name);\n}\n\nlet person = {\n    name: \"Dariana Trahan\",\n    age: 21,\n    address: \"localhost\",\n};\n\nfor (const value of Object.values(person)) {\n    console.log(value);\n}\n```\n\n# Falsy and Truthy values\n\n```js\nlet nums = [false, 0, '', \"\", ``, null, NaN, undefined];\n\nnums.map((num) =\u003e {\n    if (num) {\n        console.log(`${num} is truthy`);\n    } else {\n        console.log(`${num} is falsy`);\n    }\n})\n\n// false is falsy\n// 0 is falsy\n// is falsy\n// is falsy\n// is falsy\n// null is falsy\n// NaN is falsy\n// undefined is falsy\n```\n\n```js\nlet nums = [true, {}, [], 22, \"0\", \"false\", new Date(), -22, 3.14, -3.14, Infinity, -Infinity];\n\nnums.map((num) =\u003e {\n    if (num) {\n        console.log(`${num} is truthy`);\n    } else {\n        console.log(`${num} is falsy`);\n    }\n})\n\n// true is truthy\n// [object Object] is truthy\n// is truthy\n// 22 is truthy\n// 0 is truthy\n// false is truthy\n// Thu Sep 29 2022 15:34:49 GMT+1000 (Australian Eastern Standard Time) is truthy\n// -22 is truthy\n// 3.14 is truthy\n// -3.14 is truthy\n// Infinity is truthy\n// -Infinity is truthy\n```\n\n# Logical AND (\u0026\u0026)\n\nLogical AND (\u0026\u0026) evaluates operands from left to the right. It returns the value of the first falsy operand. If all values are truthy, it returns the value of the last operand.\n\n```js\nresult = \"\" \u0026\u0026 \"foo\"; // \"\"\nresult = 2 \u0026\u0026 0; // 0\nresult = \"foo\" \u0026\u0026 4; // 4\n```\n\n[Source](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND)\n\n# Logical OR (||)\n\nLogical OR (||) evaluates operands from left to the right. It returns the value of the first truthy operand. If all values are falsy, it returns the value of the last operand.\n\n```js\nresult = \"\" || \"foo\"; //  'foo'\nresult = 2 || 0; // 2\nresult = \"foo\" || 4; // 'foo'\n```\n\n[Source](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR)\n\n# JavaScript modules\n\nWe can export functions, var, let, const, and classes. Exported items need to be top-level items. We can't export items from a function.\n\n1. We can use the `export` statement to give access to module features.\n\n```js\n// ./modules/constants.js\nexport const PI = 3.14;\nexport const ONE = 1;\nexport const ZERO = 0;\n```\n\nThere is only zero or one default export allowed per module and zero or more Named Exports.\n\n```js\n// ./modules/random.js\n\nfunction randomString() {\n    ...\n}\n\nfunction randomFloat() {\n    ...\n}\n\nfunction randomNum() {\n    ...\n}\n\nexport { randomString, randomFloat };\nexport default randomNum;\n```\n\n```js\n// ./modules/random.js\n\nfunction randomString() {\n    ...\n}\n\nfunction randomFloat() {\n    ...\n}\n\nexport default function() {\n    ...\n}\n\nexport { randomString, randomFloat };\n```\n\n2. We can use `import` statement to get access to a module features\n\n```js\n// main.js\nimport { PI, ONE, ZERO } from \"./modules/constants.js\";\n```\n\n```js\n// main.js\nimport { randomString, randomFloat } from \"./modules/random.js\";\nimport randomNum from \"./modules/random.js\";\n```\n\n3. Renaming imports and exports\n\n```js\n// ./modules/random.js\n\nfunction randomString() {\n    ...\n}\n\nfunction randomFloat() {\n    ...\n}\n\nfunction randomNum() {\n    ...\n}\n\n\nexport {\n    randomString as newRandomStringFunctionName,\n    randomFloat as newRandomFloatFunctionName\n    randomNum as newRandomNumFunctionName\n};\n\n```\n\n```js\n// main.js\nimport {\n    newRandomStringFunctionName as randS,\n    newRandomFloatFunctionName as randF,\n    newRandomNumFunctionName as randN,\n} from \"./modules/random.js\";\n```\n\n4. Creating a module object\n\n```\nimport * as Rand from './modules/random.js';\n\nRand.newRandomStringFunctionName();\nRand.newRandomFloatFunctionName();\nRand.newRandomNumFunctionName();\n```\n\n5. No relative path\n\nThe code will look for the modules under the folder called `node_modules`.\n\n```js\nimport { Card } from \"antd\";\n```\n\n[JavaScript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules)\n\n# Promises\n\n```js\nconst myPromise = new Promise((resolve, reject) =\u003e {\n\tsetTimeout(() =\u003e {\n\t// resolve('This is the promise data');\n        reject('Something bad happened');\n\t}, 2000)\n})\n\n\nmyPromise.then((data) =\u003e {\n\tconsole.log(data);\n}, (err) =\u003e {\n    console.log(err); // Something bad happened\n})\n```\n\n## Promise chaining\n\n```js\nconst getDataPromise = (num) =\u003e new Promise((resolve, reject) =\u003e {\n    setTimeout(() =\u003e {\n        typeof num === 'number' ? resolve(num * 2) : reject('Number must be provided')\n    }, 2000)\n})\n\ngetDataPromise(10).then((data) =\u003e {\n    return getDataPromise(data)\n}).then((data) =\u003e {\n    return getDataPromise(data)\n}).then((data) =\u003e {\n    console.log(data)\n}).catch((err) =\u003e {\n    console.log(err)\n})\n```\n\n## Promise.allSettled()\n\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled\n\n# Async \u0026 Await\n\n```js\nconst getDataPromise = (num) =\u003e new Promise((resolve, reject) =\u003e {\n    setTimeout(() =\u003e {\n        typeof num === 'number' ? resolve(num * 2) : reject('Number must be provided')\n    }, 2000)\n})\n\nconst processData = async () =\u003e {\n    let data = await getDataPromise(2)\n    data = await getDataPromise(data)\n    data = await getDataPromise(data)\n    return data\n}\n\nprocessData().then((data) =\u003e {\n    console.log('Data', data)\n}).catch((error) =\u003e {\n    console.log('Error', error)\n})\n```\n\n# Constructor Functions\n\n```js\nconst Person = function (firstName, lastName, age) {\n    this.firstName = firstName;\n    this.lastName = lastName;\n    this.age = age;\n}\n\nconst person = new Person('Bob', 'Rob', 22);\nperson.age = person.age + 1;\nconsole.log(person); // Person {firstName: \"Bob\", lastName: \"Rob\", age: 23}\n```\n\n# Prototype Inheritance\n\n```js\nconst Person = function (firstName, lastName, age) {\n    this.firstName = firstName;\n    this.lastName = lastName;\n    this.age = age;\n}\n\nPerson.prototype.getBio = function () {\n    return `${this.firstName} is ${this.age}`\n}\n\nPerson.prototype.setName = function (fullName) {\n    const names = fullName.split(\" \");\n    this.firstName = names[0];\n    this.lastName = names[1];\n}\n\nconst person = new Person('Bob', 'Rob', 22);\nperson.age = person.age + 1;\nperson.setName(\"Larry Tom\");\nconsole.log(person); // Person {firstName: \"Larry\", lastName: \"Tom\", age: 23}\nconsole.log(person.getBio()); // Larry is 23\n```\n\n# Class\n\n```js\nclass Person {\n    static #PRIVATE_STATIC_FIELD;\n\n    // private fields\n    #firstName;\n    #lastName;\n    constructor(firstName, lastName, age = 0) {\n        this.#firstName = firstName;\n        this.#lastName = lastName;\n        this.age = age;\n        this.addresses = [];\n    }\n    getFullName() {\n        return this.#firstName + \" \" + this.#lastName;\n    }\n\n    // private method\n    #privateMethod() {\n        return \"hello world\";\n    }\n\n    // private static method\n    static #privateStaticMethod() {\n        return \"hello world\";\n    }\n}\n```\n\n## Subclass\n\n```js\nclass User extends Person {\n    static USER_COUNT = 0;\n    // default value for age and set address with an initial value\n    constructor(firstName, lastName, age = 0) {\n        super(firstName, lastName, age);\n        User.USER_COUNT++;\n    }\n\n    setAddress(address) {\n        this.addresses.push(address);\n    }\n\n    static getTotalUser() {\n        return this.USER_COUNT;\n    }\n}\n\nlet user = new User(\"Bob\", \"Rob\");\nconsole.log(user); // {age: 0, addresses: Array(2), #firstName: 'Bob', #lastName: 'Rob'}\nconsole.log(user.getFullName()); // Bob Rob\n\nuser.setAddress(\"15 160th Road, Wathena,ks, 66090  United States\");\nuser.setAddress(\"13 Central Avenue, Albany,ny, 12205  United States\");\n\nconsole.log(user.addresses); // ['15 160th Road, Wathena,ks, 66090  United States', '13 Central Avenue, Albany,ny, 12205  United States']\n\nconsole.log(User.USER_COUNT); // 1\n```\n\n## Getters and Setters\n\n```js\nclass Person {\n\tconstructor(firstName, lastName, age, likes = []) {\n\t\tthis.firstName = firstName;\n\t\tthis.lastName = lastName;\n\t\tthis.age = age;\n\t\tthis.likes = likes;\n\t}\n\tgetBio() {\n\t\tlet bio = `${this.firstName} is ${this.age}.`;\n\n\t\tthis.likes.forEach((like) =\u003e {\n\t\t\tbio += ` ${this.firstName} likes ${like}.`;\n\t\t});\n\n\t\treturn bio;\n\t}\n\tset fullName(fullName) {\n\t\tconst names = fullName.split(\" \");\n\t\tthis.firstName = names[0];\n\t\tthis.lastName = names[1];\n\t}\n\tget fullName() {\n\t\treturn `${this.firstName} ${this.lastName}`;\n\t}\n}\n\nclass Employee extends Person {\n\tconstructor(firstName, lastName, age, position, likes) {\n\t\tsuper(firstName, lastName, age, likes);\n\t\tthis.position = position;\n\t}\n\tgetBio() {\n\t\treturn `${this.fullName} is a ${this.position}.`;\n\t}\n\tgetYearsLeft() {\n\t\treturn 65 - this.age;\n\t}\n}\n\nclass Student extends Person {\n\tconstructor(firstName, lastName, age, grade, likes) {\n\t\tsuper(firstName, lastName, age, likes);\n\t\tthis.grade = grade;\n\t}\n\tupdateGrade(change) {\n\t\tthis.grade += change;\n\t}\n\tgetBio() {\n\t\tconst status = this.grade \u003e= 70 ? \"passing\" : \"failing\";\n\t\treturn `${this.firstName} is ${status} the class.`;\n\t}\n}\n\nconst me = new Employee(\"Andrew\", \"Mead\", 27, \"Teacher\", []);\nme.fullName = \"Clancey Turner\";\nconsole.log(me.getBio());\n```\n\n```js\nconst data = {\n    locations: [],\n    get location() {\n        return this._location;\n    },\n\n    set location(value) {\n        this._location = value.trim();\n        this.locations.push(this._location);\n    }\n}\n\ndata.location = '   Earth    ';\ndata.location = '   Mars            ';\nconsole.log(data.locations);\n```\n\n# Errors\n\n[List of errors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors#list_of_errors)\n\n## Examples\n\n1. Error\n\n2. InternalError\n\n3. RangeError\n\n4. ReferenceError\n\n5. SyntaxError\n\n6. TypeError\n\n7. URIError\n\n\n# Try Catch\n\n```js\nconst getTotalAmount = (amount) =\u003e {\n    if (typeof amount === 'number') {\n        return amount + 100;\n    } else {\n        throw Error(\"Not a number\");\n    }\n}\n\nconsole.log(getTotalAmount(12)); // 112\nconsole.log(getTotalAmount('12')); // Error: Not a number\n```\n\n```js\nconst getTotalAmount = (amount) =\u003e {\n    if (typeof amount === 'number') {\n        return amount + 100;\n    } else {\n        throw Error(\"Not a number\");\n    }\n}\n\ntry {\n    console.log(getTotalAmount(12)); // 112\n    console.log(getTotalAmount('12')); // Error: Not a number\n} catch (e) {\n    console.log(e);\n}\n```\n\n# Debugging\n\n```js\nconsole.log(\"This is a test\");\n```\n\n## Debugger\n\n```js\ndebugger;\n```\n\n## Console\n\n```js\nconsole.log(); // Outputs information to the console. Useful for general logging\nconsole.dir(input); // Displays an interactive list of the properties of the specified DOM element\nconsole.log(\"input\", input); /* or */ console.log({input});\nconsole.table(data); // Displays tabular data, suitable for array or objects\nconsole.error(\"message\"); // Outputs an error message to the console\nconsole.assert(condition, \"message\"); // Logs a message if the condition is false\nif(data === undefined)\n    console.error(\"This should not happen\"); // Red color\nconsole.assert(data !== undefined, \"This should not happen\");\nconsole.warn(\"message\"); // Outputs a warning message to the console in yellow color\nconsole.time(\"label\"); /* the code you want to measure for performance */ console.timeEnd(\"label\"); // Starts/ends a timer you can use to track how long an operation takes\n```\n\n## Breakpoints\n\nAt each breakpoint, JavaScript will stop executing, and let you examine JavaScript values\n\n\n[source](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger)\n\n# HTML with live server\n\n```shell\nnpm install -g live-server\nlive-server --version\n// live-server 1.2.2\n\nmkdir folder_name\ncd folder_name\n```\n\nNow create a file called `index.html` inside the folder `folder_name` with the following content.\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n    \u003chead\u003e\n        \u003cmeta charset=\"UTF-8\" /\u003e\n        \u003cmeta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /\u003e\n        \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /\u003e\n        \u003ctitle\u003eDocument\u003c/title\u003e\n    \u003c/head\u003e\n    \u003cbody\u003e\n        Hello World\n    \u003c/body\u003e\n\u003c/html\u003e\n```\n\nStart the live server.\n\n```shell\nlive-server folder_name\n// Serving \"folder_name\" at http://127.0.0.1:8080\n// Ready for changes\n```\n\nAlernatively you can use this [VSCode Extension](https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer).\n\n[Source](https://developer.mozilla.org/en-US/docs/Web/HTML/Element)\n\n# How to add JavaScript to a web page\n\n## Everything between script tags will be executed by the web browser\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n    \u003chead\u003e\n        \u003cmeta charset=\"UTF-8\" /\u003e\n        \u003cmeta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /\u003e\n        \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /\u003e\n        \u003ctitle\u003eDocument\u003c/title\u003e\n    \u003c/head\u003e\n    \u003cbody\u003e\n        Hello, World!\n    \u003c/body\u003e\n\n    \u003cscript type=\"text/javascript\"\u003e\n        alert(\"Hello, World!\");\n    \u003c/script\u003e\n\u003c/html\u003e\n```\n\nGet the code from [here](https://github.com/lifeparticle/JS-Cheatsheet/tree/main/examples/example-1).\n\n## Link an external file to a web page\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n    \u003chead\u003e\n        \u003cmeta charset=\"UTF-8\" /\u003e\n        \u003cmeta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /\u003e\n        \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /\u003e\n        \u003ctitle\u003eDocument\u003c/title\u003e\n    \u003c/head\u003e\n    \u003cbody\u003e\n        Hello, World!\n    \u003cscript type=\"text/javascript\" src=\"index.js\"\u003e\u003c/script\u003e\n    \u003c/body\u003e\n\u003c/html\u003e\n```\n\nGet the code from [here](https://github.com/lifeparticle/JS-Cheatsheet/tree/main/examples/example-2).\n\n# DOM - Document Object Model\n\n## DOM manipulation\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n    \u003chead\u003e\n        \u003cmeta charset=\"UTF-8\" /\u003e\n        \u003cmeta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /\u003e\n        \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /\u003e\n        \u003ctitle\u003eDocument\u003c/title\u003e\n    \u003c/head\u003e\n    \u003cbody\u003e\n        \u003cp\u003eHello World\u003c/p\u003e\n        \u003cscript type=\"text/javascript\" src=\"index.js\"\u003e\u003c/script\u003e\n    \u003c/body\u003e\n\u003c/html\u003e\n```\n\n```js\nconst p = document.querySelector(\"p\");\nconsole.log(p);\np.remove();\n```\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n    \u003chead\u003e\n        \u003cmeta charset=\"UTF-8\" /\u003e\n        \u003cmeta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /\u003e\n        \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /\u003e\n        \u003ctitle\u003eDocument\u003c/title\u003e\n    \u003c/head\u003e\n    \u003cbody\u003e\n        \u003cp\u003eHello World\u003c/p\u003e\n        \u003cp\u003eHello Universe\u003c/p\u003e\n        \u003cscript type=\"text/javascript\" src=\"index.js\"\u003e\u003c/script\u003e\n    \u003c/body\u003e\n\u003c/html\u003e\n```\n\n```js\nconst ps = document.querySelectorAll(\"p\");\nconsole.log(ps);\n\nps.forEach((p) =\u003e {\n    p.remove();\n});\n\nconst newParagraph = document.createElement(\"p\");\nnewParagraph.textContent = \"This is a new element from JavaScript\";\ndocument.querySelector(\"body\").appendChild(newParagraph);\n```\n## Event handling\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n    \u003chead\u003e\n        \u003cmeta charset=\"UTF-8\" /\u003e\n        \u003cmeta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /\u003e\n        \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /\u003e\n        \u003ctitle\u003eDocument\u003c/title\u003e\n    \u003c/head\u003e\n    \u003cbody\u003e\n        \u003ch1\u003eNotes\u003c/h1\u003e\n        \u003cbutton\u003eCreate note\u003c/button\u003e\n        \u003cscript type=\"text/javascript\" src=\"index.js\"\u003e\u003c/script\u003e\n    \u003c/body\u003e\n\u003c/html\u003e\n```\n\n```js\nlet notes = [\n    {\n        title: \"First title\",\n        body: \"First body\",\n    },\n    {\n        title: \"Second title\",\n        body: \"Second body\",\n    },\n    {\n        title: \"Third title\",\n        body: \"Third body\",\n    },\n];\n\ndocument.querySelector(\"button\").addEventListener(\"click\", (e) =\u003e {\n    console.log(`${e.target.textContent} Button is clicked`);\n});\n```\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n    \u003chead\u003e\n        \u003cmeta charset=\"UTF-8\" /\u003e\n        \u003cmeta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /\u003e\n        \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /\u003e\n        \u003ctitle\u003eDocument\u003c/title\u003e\n    \u003c/head\u003e\n    \u003cbody\u003e\n        \u003ch1\u003eNotes\u003c/h1\u003e\n        \u003cp class=\"note\"\u003eNote 1\u003c/p\u003e\n        \u003cp class=\"note\"\u003eNote 2\u003c/p\u003e\n        \u003cp class=\"note\"\u003eNote 3\u003c/p\u003e\n        \u003cbutton id=\"create-note\"\u003eCreate note\u003c/button\u003e\n        \u003cbutton id=\"remove-all\"\u003eRemove all notes\u003c/button\u003e\n        \u003cscript type=\"text/javascript\" src=\"index.js\"\u003e\u003c/script\u003e\n    \u003c/body\u003e\n\u003c/html\u003e\n```\n\n```js\nlet notes = [\n    {\n        title: \"First title\",\n        body: \"First body\",\n    },\n    {\n        title: \"Second title\",\n        body: \"Second body\",\n    },\n    {\n        title: \"Third title\",\n        body: \"Third body\",\n    },\n];\n\ndocument.getElementById(\"create-note\").addEventListener(\"click\", (e) =\u003e {\n    console.log(`${e.target.textContent} Button is clicked`);\n});\n\ndocument.getElementById(\"remove-all\").addEventListener(\"click\", (e) =\u003e {\n    console.log(`Delete all notes`);\n    [...document.getElementsByClassName(\"note\")].forEach((note) =\u003e {\n        note.remove();\n    });\n});\n```\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n    \u003chead\u003e\n        \u003cmeta charset=\"UTF-8\" /\u003e\n        \u003cmeta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /\u003e\n        \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /\u003e\n        \u003ctitle\u003eDocument\u003c/title\u003e\n    \u003c/head\u003e\n    \u003cbody\u003e\n        \u003ch1\u003eNotes\u003c/h1\u003e\n        \u003cp class=\"note\"\u003eNote 1\u003c/p\u003e\n        \u003cp class=\"note\"\u003eNote 2\u003c/p\u003e\n        \u003cp class=\"note\"\u003eNote 3\u003c/p\u003e\n        \u003cinput id=\"search-note\" type=\"text\" /\u003e\n        \u003cbutton id=\"create-note\"\u003eCreate note\u003c/button\u003e\n        \u003cbutton id=\"remove-all\"\u003eRemove all notes\u003c/button\u003e\n        \u003cscript type=\"text/javascript\" src=\"index.js\"\u003e\u003c/script\u003e\n    \u003c/body\u003e\n\u003c/html\u003e\n```\n\n```js\nlet notes = [\n    {\n        title: \"First title\",\n        body: \"First body\",\n    },\n    {\n        title: \"Second title\",\n        body: \"Second body\",\n    },\n    {\n        title: \"Third title\",\n        body: \"Third body\",\n    },\n];\n\ndocument.getElementById(\"create-note\").addEventListener(\"click\", (e) =\u003e {\n    console.log(`${e.target.textContent} Button is clicked`);\n});\n\ndocument.getElementById(\"remove-all\").addEventListener(\"click\", (e) =\u003e {\n    console.log(`Delete all notes`);\n    [...document.getElementsByClassName(\"note\")].forEach((note) =\u003e {\n        note.remove();\n    });\n});\n\ndocument.getElementById(\"search-note\").addEventListener(\"input\", (e) =\u003e {\n    console.log(`${e.target.value}`);\n});\n```\n\n[Source](https://developer.mozilla.org/en-US/docs/Glossary/Empty_element)\n\n\nThere are two types of event propagation: Event bubbling and Event capturing.\n\n### Event bubbling\n\nEvent is captured by the inner clciked element and propagated to outer elements. Also, we can stop propagation.\n\n```html\n\u003chtml\u003e\n    \u003chead\u003e\n        \u003cscript src=\"index.pack.js\"\u003e\u003c/script\u003e\n    \u003c/head\u003e\n    \u003cbody\u003e\n        \u003cdiv id=\"parent\"\u003e\n            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse egestas lectus id massa convallis fermentum. Aenean pulvinar interdum viverra. Maecenas porttitor lorem in velit placerat, et blandit ex pellentesque. Nunc convallis fermentum ullamcorper. Suspendisse malesuada euismod quam et dapibus. Mauris eget ligula urna. Sed lacinia ex a libero interdum, ac pellentesque lectus posuere. Nunc tristique mattis mollis. Mauris suscipit augue ante, efficitur consectetur nulla pulvinar at. Curabitur vitae placerat tortor.\n\n            Ut vitae neque sit amet turpis tempor fermentum. Proin a velit tellus. Sed vitae tincidunt ex, vel varius ante. Mauris at est arcu. Proin a suscipit lacus, sed venenatis metus. Donec efficitur quis mi nec porttitor. Nulla luctus nisi erat. Praesent id nibh congue, placerat magna non, lacinia tortor. Quisque dignissim in ante quis euismod. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Duis eget enim imperdiet, maximus ante vitae, bibendum tortor. Morbi molestie lacus rhoncus, tempor magna sit amet, semper libero. Nam ipsum ipsum, ultricies vel dignissim id, molestie quis nisl. Pellentesque et quam elementum, rhoncus ipsum a, suscipit nulla.\n            \u003c/br\u003e\n            \u003cbutton id=\"bt1\"\u003eSubmit\u003c/button\u003e\n        \u003c/div\u003e\n    \u003c/body\u003e\n\u003c/html\u003e\n```\n\n```js\nconst parent = document.getElementById(\"parent\");\nconst bt1 = document.getElementById(\"bt1\");\n\nparent.addEventListener(\"click\", (e) =\u003e {\n    console.log(\"Parent is clicked\");\n})\n\nbt1.addEventListener(\"click\", (e) =\u003e {\n    console.log(\"bt1 is clicked\");\n})\n\ndocument.addEventListener(\"click\", (e) =\u003e {\n    console.log(\"document is clicked\");\n})\n```\n\n// When bt1 is clicked\n\n```\nbt1 is clicked\nParent is clicked\ndocument is clicked\n```\n\n```js\nconst parent = document.getElementById(\"parent\");\nconst bt1 = document.getElementById(\"bt1\");\n\nparent.addEventListener(\"click\", (e) =\u003e {\n    console.log(\"Parent is clicked\");\n})\n\nbt1.addEventListener(\"click\", (e) =\u003e {\n    console.log(\"bt1 is clicked\");\n    e.stopPropagation();\n})\n\ndocument.addEventListener(\"click\", (e) =\u003e {\n    console.log(\"document is clicked\");\n})\n```\n\n// When bt1 is clicked\n\n```\nbt1 is clicked\n```\n\n```js\nconst parent = document.getElementById(\"parent\");\nconst bt1 = document.getElementById(\"bt1\");\n\nparent.addEventListener(\"click\", (e) =\u003e {\n    console.log(\"Parent is clicked\");\n})\n\nbt1.addEventListener(\"click\", (e) =\u003e {\n    console.log(\"bt1 is clicked\");\n})\n\ndocument.addEventListener(\"click\", (e) =\u003e {\n    console.log(\"document is clicked\");\n})\n```\n\n// When bt1 is clicked\n\n```\nbt1 is clicked\nParent is clicked\ndocument is clicked\n```\n\n// When bt1 is clicked\n\n```\nParent is clicked\ndocument is clicked\n```\n\n```html\n\u003chtml\u003e\n    \u003chead\u003e\n        \u003cscript src=\"index.pack.js\"\u003e\u003c/script\u003e\n    \u003c/head\u003e\n    \u003cbody\u003e\n        \u003cdiv id=\"super-parent\"\u003e\n            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse egestas lectus id massa convallis fermentum. Aenean pulvinar interdum viverra. Maecenas porttitor lorem in velit placerat, et blandit ex pellentesque. Nunc convallis fermentum ullamcorper. Suspendisse malesuada euismod quam et dapibus. Mauris eget ligula urna. Sed lacinia ex a libero interdum, ac pellentesque lectus posuere. Nunc tristique mattis mollis. Mauris suscipit augue ante, efficitur consectetur nulla pulvinar at. Curabitur vitae placerat tortor.\n            \u003c/br\u003e\n            \u003c/br\u003e\n            \u003c/br\u003e\n            \u003cdiv id=\"parent\"\u003e\n                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse egestas lectus id massa convallis fermentum. Aenean pulvinar interdum viverra. Maecenas porttitor lorem in velit placerat, et blandit ex pellentesque. Nunc convallis fermentum ullamcorper. Suspendisse malesuada euismod quam et dapibus. Mauris eget ligula urna. Sed lacinia ex a libero interdum, ac pellentesque lectus posuere. Nunc tristique mattis mollis. Mauris suscipit augue ante, efficitur consectetur nulla pulvinar at. Curabitur vitae placerat tortor.\n\n                Ut vitae neque sit amet turpis tempor fermentum. Proin a velit tellus. Sed vitae tincidunt ex, vel varius ante. Mauris at est arcu. Proin a suscipit lacus, sed venenatis metus. Donec efficitur quis mi nec porttitor. Nulla luctus nisi erat. Praesent id nibh congue, placerat magna non, lacinia tortor. Quisque dignissim in ante quis euismod. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Duis eget enim imperdiet, maximus ante vitae, bibendum tortor. Morbi molestie lacus rhoncus, tempor magna sit amet, semper libero. Nam ipsum ipsum, ultricies vel dignissim id, molestie quis nisl. Pellentesque et quam elementum, rhoncus ipsum a, suscipit nulla.\n                \u003c/br\u003e\n                \u003cbutton id=\"bt1\"\u003eSubmit\u003c/button\u003e\n            \u003c/div\u003e\n        \u003c/div\u003e\n    \u003c/body\u003e\n\u003c/html\u003e\n```\n\n```js\nconst parent = document.getElementById(\"parent\");\nconst bt1 = document.getElementById(\"bt1\");\n\nconst addGlobalEventListener = (eventType, cssSelector, id, callback) =\u003e {\n    document.addEventListener(eventType, (e) =\u003e {\n        if(e.target.matches(cssSelector) \u0026\u0026 event.target.id === id)\n            callback(e);\n    })\n}\n\naddGlobalEventListener('click', 'div', 'parent', (e) =\u003e {\n    console.log(\"parent is clicked\");\n})\n\n```\n\n### Event capturing\n\nEvent is captured by the outer clciked element and propagated to inner elements. Also, we can stop propagation.\n\n```js\nconst parent = document.getElementById(\"parent\");\nconst bt1 = document.getElementById(\"bt1\");\n\nparent.addEventListener(\"click\", (e) =\u003e {\n    console.log(\"Parent is clicked\");\n} , {capture: true})\n\nbt1.addEventListener(\"click\", (e) =\u003e {\n    console.log(\"bt1 is clicked\");\n})\n\ndocument.addEventListener(\"click\", (e) =\u003e {\n    console.log(\"document is clicked\");\n})\n```\n\n// When bt1 is clicked\n\n```\nParent is clicked\nbt1 is clicked\ndocument is clicked\n```\n\n```js\nconst parent = document.getElementById(\"parent\");\nconst bt1 = document.getElementById(\"bt1\");\n\nparent.addEventListener(\"click\", (e) =\u003e {\n    console.log(\"Parent is clicked\");\n    e.stopPropagation();\n} , {capture: true})\n\nbt1.addEventListener(\"click\", (e) =\u003e {\n    console.log(\"bt1 is clicked\");\n})\n\ndocument.addEventListener(\"click\", (e) =\u003e {\n    console.log(\"document is clicked\");\n})\n```\n\n// When bt1 is clicked\n\n```\nParent is clicked\n```\n\n# Local Storage\n\n```js\nlocalStorage.setItem(\"your_key\", \"your_value\");\nlocalStorage.getItem(\"your_key\");\nlocalStorage.localStorage.removeItem(\"your_key\");\nlocalStorage.clear();\n```\n\n```js\nlocalStorage.setItem(\"your_key\", JSON.stringify(\"your_value\"))\nlocalStorage.getItem(JSON.parse(\"your_key\"));\n```\n\n# Window interface\n\n```js\nwindow.console.log(\"Hello\");\nwindow.document === document;\n```\n\n```js\nwindow.addEventListener('click', () =\u003e {\n    console.log(\"Clicked\");\n})\n```\n\nlocalStorage Sync across pages: The storage event of the Window interface fires when a localStorage is changed in the context of another document. So the storage event does not fire for the document that is responsible for the localStorage changes; it will fire the storage event for the other documents. In simple words if we have 3 tabs open, and if tab1 changes the localStorage then only tab2 and tab3 will fire storage event.\n\n```js\nwindow.addEventListener('storage', () =\u003e {\n    console.log(\"Clicked\");\n})\n```\n\n# Strict mode\n\n```js\nconst getNumber = () =\u003e {\n    data = '112122';\n}\n\ngetNumber();\nconsole.log(data); // 112122\n```\n\n\n```js\n'use strict'\n\nconst getNumber = () =\u003e {\n    data = '112122';\n}\n\ngetNumber();\nconsole.log(data); // Uncaught ReferenceError: data is not defined\n```\n\n# HTTP requests\n\n```js\nconst request = new XMLHttpRequest();\nrequest.addEventListener(\"readystatechange\", (e) =\u003e {\n\tif (e.target.readyState === 4 \u0026\u0026 e.target.status === 200) {\n\t\tconst data = JSON.parse(e.target.responseText);\n\t\tconsole.log(data);\n\t} else if (e.target.readyState === 4) {\n\t\tconsole.log(\"error\");\n\t}\n});\nrequest.open(\"GET\", \"https://puzzle.mead.io/puzzle\");\nrequest.send();\n```\n\n## Callback pattern - Asynchronous execution\n\n```js\nconst getPuzzle = (callback) =\u003e {\n\tconst request = new XMLHttpRequest();\n\trequest.addEventListener(\"readystatechange\", (e) =\u003e {\n\t\tif (e.target.readyState === 4 \u0026\u0026 e.target.status === 200) {\n\t\t\tconst data = JSON.parse(e.target.responseText);\n\t\t\tcallback(undefined, data);\n\t\t} else if (e.target.readyState === 4) {\n\t\t\tcallback(\"An error has taken place\", undefined);\n\t\t\tconsole.log(\"error\");\n\t\t}\n\t});\n\trequest.open(\"GET\", \"https://puzzle.mead.io/puzzle\");\n\trequest.send();\n};\n\ngetPuzzle((error, puzzle) =\u003e {\n\tif (error) {\n\t\tconsole.log(`Error: ${error}`);\n\t} else {\n\t\tconsole.log(puzzle);\n\t}\n});\n```\n\n## Synchronous execution\n\n```js\nconst getPuzzleSync = () =\u003e {\n\tconst request = new XMLHttpRequest();\n\trequest.open(\"GET\", \"https://puzzle.mead.io/puzzle\", false);\n\trequest.send();\n\n\tif (request.readyState === 4 \u0026\u0026 request.status === 200) {\n\t\tconst data = JSON.parse(request.responseText);\n\t\treturn data;\n\t} else if (request.readyState === 4) {\n\t\tconsole.log(\"error\");\n\t\tthrow new Error(\"Something bad happend\");\n\t}\n};\n\nconsole.log(getPuzzleSync());\n```\n## Fetch API\n\n```js\nfetch('http://puzzle.mead.io/puzzle', {}).then((response) =\u003e {\n    if (response.status === 200) {\n        return response.json()\n    } else {\n        throw new Error('Unable to fetch the puzzle')\n    }\n}).then((data) =\u003e {\n    console.log(data.puzzle)\n}).catch((error) =\u003e {\n    console.log(error)\n})\n```\n\n# Closure\n\n```js\nconst getPrint = () =\u003e {\n    const print = (message) =\u003e {\n        console.log(message)\n    }\n    return print;\n}\n\nconst value = getPrint();\nvalue(\"Closure\"); // Closure\n```\n\n```js\nconst createCounter = () =\u003e {\n    let count = 0;\n\n    return {\n        increment() {\n            count++;\n        },\n        decrement() {\n            count--;\n        },\n        get() {\n            return count;\n        }\n    }\n}\n\nconst counter = createCounter();\ncounter.increment();\ncounter.decrement();\ncounter.decrement();\nconsole.log(counter.get()); // -1\n```\n\n# Currying\n\n```js\nfunction add(a, b) {\n    return a + b;\n}\n\nconsole.log(add(3 + 4)); // 7\n\n\nfunction add(a) {\n    return function(b) {\n        return a + b;\n    }\n}\n\nconst fnB = add(3);\nconsole.log(fnB(4)); // 7\n\n// or\nconsole.log(add(3)(4));\n\n\nconst add = a =\u003e b =\u003e a + b;\n\nconsole.log(add(3)(4)); // 7\n```\n\n# Pure function\n\nA pure function is a function that, given the same input, will always return the same output, and does not have any side effects (such as modifying external state or interacting with the outside world). Pure functions are predictable and easier to test.\n\n```js\n//        same arguments\nfunction add(a, b) {\n//   same result\n  return a + b;\n}\n\nconsole.log(add(2, 3)); // Always returns 5\nconsole.log(add(2, 3)); // Always returns 5\n```\n\n## A non-pure function\n\n```js\nlet counter = 0;\n\nfunction incrementCounter() {\n  counter += 1;\n  return counter;\n}\n\nconsole.log(incrementCounter()); // Output: 1\nconsole.log(incrementCounter()); // Output: 2\nconsole.log(incrementCounter()); // Output: 3\n```\n\n# Sleep\n\n```js\nconst sleep = (time) =\u003e {\n  const date = Date.now();\n  let currentDate;\n  do {\n    currentDate = Date.now();\n  } while (currentDate - date \u003c time);\n}\n\nconsole.log(\"Before sleep\");\nsleep(2000);\nconsole.log(\"After sleep\");\n```\n\n# Performance\n\n```js\nconsole.time(\"name\")\nconsole.timeEnd(\"name\")\n```\n\n# Math\n\n`Math.random()` generates a random floating-point number between 0 (inclusive) and 1 (exclusive).\n\n\n```js\nMath.random();\n```\n\n```js\nfunction randomRange(min, max) {\n  return Math.floor(Math.random() * (max - min + 1)) + min;\n}\n```\n\n# Feature detection\n\n```js\nif ('localStorage' in window) {\n    console.log(\"Have localStorage support\");\n}\n```\n\n# Resources\n\n1. [Learn Typescript for free](https://scrimba.com/learn/typescript)\n2. [Learn JavaScript for free](https://scrimba.com/learn/learnjavascript)\n3. [Loops and iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration)\n4. [Javascript refresher](https://github.com/Asabeneh/30-Days-Of-React/blob/master/01_Day_JavaScript_Refresher/01_javascript_refresher.md)\n5. [ecma-international](https://www.ecma-international.org/about-ecma/history/)\n6. [Why-does-my-variable-show-its-deprecated](https://stackoverflow.com/questions/65379554/why-does-my-variable-show-its-deprecated)\n7. [You Don't Know JS Yet](https://github.com/getify/You-Dont-Know-JS)\n8. [JavaScript](https://github.com/Asabeneh/30-Days-Of-JavaScript)\n9. [Webpack](https://webpack.js.org/concepts/why-webpack/)\n10. [Polyfill](https://developer.mozilla.org/en-US/docs/Glossary/Polyfill)\n11. [Babel-polyfill](https://babeljs.io/docs/en/babel-polyfill/)\n","projects_url":"https://awesome.ecosyste.ms/api/v1/lists/lifeparticle%2Fjs-cheatsheet/projects"}