{"id":15563177,"url":"https://github.com/tush-tr/javascript-is-love","last_synced_at":"2025-04-23T23:20:38.869Z","repository":{"id":104217105,"uuid":"354214738","full_name":"tush-tr/JavaScript-is-love","owner":"tush-tr","description":"Amazing JavaScript learning and practice questions","archived":false,"fork":false,"pushed_at":"2023-06-21T05:59:44.000Z","size":251,"stargazers_count":11,"open_issues_count":0,"forks_count":2,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-30T04:31:43.095Z","etag":null,"topics":["angular","javascript","nodejs","nodejs-modules","react","typescript"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tush-tr.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"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}},"created_at":"2021-04-03T06:08:28.000Z","updated_at":"2024-01-31T16:57:49.000Z","dependencies_parsed_at":null,"dependency_job_id":"f6bf223c-02d2-40b4-bf76-40695b93a8b8","html_url":"https://github.com/tush-tr/JavaScript-is-love","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tush-tr%2FJavaScript-is-love","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tush-tr%2FJavaScript-is-love/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tush-tr%2FJavaScript-is-love/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tush-tr%2FJavaScript-is-love/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tush-tr","download_url":"https://codeload.github.com/tush-tr/JavaScript-is-love/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250529611,"owners_count":21445654,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["angular","javascript","nodejs","nodejs-modules","react","typescript"],"created_at":"2024-10-02T16:20:18.697Z","updated_at":"2025-04-23T23:20:38.838Z","avatar_url":"https://github.com/tush-tr.png","language":"JavaScript","readme":"# JavaScript all concepts\nAmazing JavaScript learning and practice questions\n\n### Content\n\u003cli\u003e\u003ca href=\"#valuesandvariables\"\u003eValues and Variables- Premitive data types- Numbers\u003c/a\u003e\n\u003cli\u003e\u003ca href=\"#howjs\"\u003eHow JavaScript works?\u003c/a\u003e\n\u003cli\u003e\u003ca href=\"#premitive2\"\u003ePremitive data types- Boolean, Null, Undefined, String\u003c/a\u003e\n\u003cli\u003e\u003ca href=\"#control-flow\"\u003e Control and logic flow- if/else, switch, ternary operator, logical operators etc.\u003c/a\u003e\n\u003cli\u003e\u003ca href=\"#arrays\"\u003eArrays, array methods\u003c/a\u003e\n\u003cli\u003e\u003ca href=\"#objects\"\u003eObjects in JavaScript\u003c/a\u003e\n\u003cli\u003e\u003ca href=\"#loops\"\u003eLoops in JavaScript\u003c/a\u003e\n\u003cli\u003e\u003ca href=\"#functions\"\u003eFunctions in JavaScript\u003c/a\u003e\n\u003cli\u003e\u003ca href=\"#scope\"\u003eScope,Function expressions, Higher Order functions, callbacks, hoisting\u003c/a\u003e\n\u003cli\u003e\u003ca href=\"#arraymethods\"\u003eArray callback methods- filter, forEach, reduce, map, some, every etc.\n\u003c/a\u003e\n\u003cli\u003e\u003ca href=\"#more-js\"\u003eDefault Parameters, Spreads,Rest Parameters, Destructuring\u003c/a\u003e\n\u003cli\u003e\u003ca href=\"#objectmethods\"\u003eObject Methods and the \"This\" Keyword\u003c/a\u003e\n\u003cli\u003e\u003ca href=\"#dom\"\u003eDocument Object Model\u003c/a\u003e\n\u003cli\u003e\u003ca href=\"#events\"\u003eCommunicating with Events\u003c/a\u003e\n\u003cli\u003e\u003ca href=\"#async\"\u003eAsynchronous JavaScript, Callbacks and Promises\u003c/a\u003e\n\u003cli\u003e\u003ca href=\"#making-requests\"\u003eMaking http requests: Fetch, Axios\u003c/a\u003e\n\u003cli\u003e\u003ca href=\"#async-await\"\u003eAsync and Await \u003c/a\u003e\n\u003cli\u003e\u003ca href=\"#oops\"\u003ePrototypes, Classes, \u0026 the new operator\u003c/a\u003e\n\u003cli\u003e\u003ca href=\"#node\"\u003eJavaScript with Node.js\u003c/a\u003e\n\u003cbr\u003e\u003cbr\u003e\n\n\n\u003ch1 id=\"valuesandvariables\"\u003e Values and variables\u003c/h1\u003e\n\n## Primitive Data types\nevery language out there has a group of types.\nDifferent categories for data.\n\u003cli\u003eNumber - its a numeric value\n\u003cli\u003eString - text words, could be a number but inside quotation marks\n\u003cli\u003eBoolean - true or false values\n\u003cli\u003eNull\n\u003cli\u003eUndefined\n\u003cli\u003etechnically there are two others- Symbol and BigInt\n\n## Numbers in JS\nJS has one number type\n\u003cli\u003epositive numbers\n\u003cli\u003enegative numbers\n\u003cli\u003ewhole number (integers)\n\u003cli\u003eDecimal Numbers(floats)\n\n\u003e clear() - clears the console\n\nwith numbers we have different mathematical operations that we can use kind of like a calculator.\n\n\u003e Addition\u003cbr\u003e 13+15\n\n\u003e Substraction\u003cbr\u003e 15-2\n\n\u003e Multiply\u003cbr\u003e 12*3\n\n\u003e Divide \u003cbr\u003e 12/6\n\n\u003e Modulo \u003cbr\u003e 12%4 - returns the remainder\n\n\u003e // \u003cb\u003eComments\u003c/b\u003e after these two forward slashes\n\n\n#### exponent or exponential operator\nwhich looks like this two star star.\n\u003e 4 ** 2 = 16\n\n### NAN Not a Number\nNaN is a numeric value that represents something that is not a number.\n\u003e 0/0 = NaN\n\n\u003e 122 + NaN = NaN\n\nIt doesn't necessarily mean something went wrong.\n\n\n### Infinity\nwhich we can generate by doing something like\n1 divided by zero javascript just has a way of representing a value of infinity.\n\u003e 1/0 = infinity\n\n\u003chr\u003e\n\n\n# Variables\n\nVariables are like \"labeled jars\" for a value in JavaScript.\n\nWe can store a value and give it a name, so that we can--\n\n\u003cli\u003eRecall it\n\u003cli\u003eUse it\n\u003cli\u003eOr change it later on\n\n the basic syntax that we'll see first is using a keyword called let.\n```javascript\nlet age = 14;\n```\nNow there actually are two different ways that we can create variables in JavaScript at least two that\nare commonly used today.\n\nhow to update a variable\n```javascript\nage = age +1;\n```\nwe should always keep our variable names in camel case like this\n```js\nlet ageOfTushar = 20;\n```\n## Unary operators\nunary operators are operators where there's only one side.\n```js\nlet counter = 1;\ncounter++;\n```\n\n## Const\nconst is just like let except we can't change the value.\n\n## legacy of var\nbefore let and const , var was only way to declare the variables. Now there's no reason to use it.\n\nlets talk about other primitive data types-\n\u003ch1 id=\"premitive2\"\u003e Booleans\u003c/h1\u003e\nbooleans are simply true or false values.\n\n```js\nlet isFriend = true;\nisFriend = false;\n```\n\n-- in javascript we can change type of variables.\nif you have experience with any other programming language well maybe not any other but many other\nlanguages.\nWhen you declare a variable and you make it a number it needs to stay a number in JavaScript there is\nno restriction on that.\nWe can change a number to a Boolean at any point.\n\nThat's not saying it's a good idea at all.\nIn fact it's one of the things a lot of people don't like about JavaScript and it's why things like\nTypeScript exist.\n\n# Strings\nstrings are pieces of text, or strings of characters.We wrap them in quotes.\n\n```js\nlet rh = \"This is going to be a good book\";\n\"hi\" + 1\n\u003e \"hi1\"\n\"hi\" - 1\n\u003eNaN\n```\n\n\u003e Strings are indexed\nevery character has a corresponding index.\nwe can check length of a string using:\n```js\nlet s = \"Tushar\"\nlet lengthOfs = s.length\n// accessing individual characters of a string using it's index\nconsole.log(s[0])\n// access last character of a string\nconsole.log(s[s.length - 1])\n// change characters \ns[1] = \"u\"\n// we can't change strings individual characters this way\n```\n\u003e strings are immutable in javascript\n\n## String methods\nstrings come with a set of built in methods. which are actions that can be performed on or with that particular string.\n```js\nthing.method()\n```\n\n### toUpperCase()\n```js\nlet s = \"tushar\";\ns.toUpperCase(); // returns new string with UPPER case\n```\n\n### toLowerCase()\n```js\ns.toLowerCase();// returns new string with all lowercase characters\n```\n\n### trim()\nIt just removes trailing leading and trailing whitespace so spaces at the beginning and\nend of a string when you call trim it returns a string where that space has been removed.\n```js\ns.trim()\n```\n\n## Methods with arguments\nsome methods accepts arguments that modify their behaviour.\n```js\nthing.method(args)\n```\n\n### indexOf()\ntell you where in a string a given string occurs substring.\n\n```js\nlet st = \"Tushar Rajpoot\";\nst.indexOf(\"u\") // returns the index\nst.indexof(\"www\") // return -1 not found\n```\n\n### slice()\ntakes index and gives sliced string\n```js\nlet s = \"Tushar\";\ns.slice(0,3);\n\u003e\"Tus\"\n```\n\n### replace()\nreturns a new string with replaced substring\n```js\nlet as = \"I'm Tushar and I'm a programmer\";\nas.replace(\"programmer\",\"developer\")\n\u003e\"I'm Tushar and I'm a developer\"\n```\n\n## String espace characters\n\n\u003cli\u003e \\n - newline\n\u003cli\u003e \\' - single quote\n\u003cli\u003e \\\" - double quote\n\u003cli\u003e\\\\ - backslash\n\n## String template literals\ntemplate literals are strings that allow embedded expressions, which will be evaluated and then turned into a resulting string.\n\nuse backtick for string template literals\n\n```js\nlet tu = 13;\nlet s = `Number of tushar- ${tu}`\n```\n\n# Null and Undefined\n### Null\nIntentional absence of any value.\u003cbr\u003e Must be assigned.\n\n### Undefined\nVariables that don't have an assigned value are undefined.\n\n```js\nlet logg = null;\n```\n\n# Math object\ncontains properties and methods for mathematical constantss and functions.\n\n```js\nMath.PI // 3.14...\n\n//Rounding a number\nMath.round(4.9) // 5\n\n// Absolute value\nMath.abs(-456) // 456\n\n// Raises 2 to 5th power\nMath.pow(2,5) // 32\n\n// Removes decimal\nMath.floor(3.23) // 3\n```\n\n## Random numbers\nMath.random() gives us a random decimal between 0 and 1 (non- inclusive)\n\n```js\nMath.random() // it will return random decimal number between 0 and 1\n// 0.33493\n\n// genrate random number between 1 to 10\nconst step1 = Math.random();\nconst step2 = step1 * 10;\nconst step3 = Math.floor(step2);\nconst step4 = step3 +1;\n\n// so basically we can do like this\nMath.floor(Math.random() * 10)+1;\n\n```\n\n## TYPE OF\nwe use type of to determine type of a given value.\n\n```js\nlet s = \"tus\";\ntypeof(s)// return string\n// we can use without these parentheses also\ntypeof tu\n```\n\n# parseInt and parseFloat\nuse to parse strings into numbers, but watch out for NaN.\n```js\nlet str = \"123\"\nparseInt(str)\n\u003e123\nlet s = \"1.2\"\nparseFloar(s);\n\u003e1.2\nlet st = \"w1\"\nparseInt(st);\n\u003eNaN\n```\n\n\n\n\n  \u003ch1 align=\"center\" id=\"howjs\"\u003eHow code is executed in JavaScript\u003c/h1\u003e\n  \u003ch3\u003eExecution Context\u003c/h3\u003e\n  Everything in JavaScript happens inside an execution context.\u003cbr\u003e\nAssume it like a big box or container in which JS code is executed.\u003cbr\u003e\n\u003cb\u003eExecution context is a wrapper around your existing code; which contains code that you have not written, but is generated by JS engine.\u003c/b\u003e\n\u003cbr\u003e A JavaScript execution context is created each time when you run your JS code file.\n  \n  \u003ctable align=\"center\" style=\"border:solid black;margin-top:20px\"\u003e\n    \u003ctbody\u003e\u003ctr style=\"border:solid black\"\u003e\n      \u003cth style=\"border:solid black\"\u003eMemory Component\u003c/th\u003e\n      \u003cth style=\"border:solid black\"\u003eCode Component\u003c/th\u003e\n    \u003c/tr\u003e\n    \u003ctr style=\"border:solid black;height:100px\"\u003e\n      \u003ctd style=\"border:solid black\"\u003eMemory allocation of variables\u003c/td\u003e\n      \u003ctd style=\"border:solid black\"\u003eCode execution\u003c/td\u003e\n    \u003c/tr\u003e\n  \u003c/tbody\u003e\u003c/table\u003e\n  \n  \u003ch3\u003eComponents of execution context\u003c/h3\u003e\n  \u003cli\u003eMemory Component\u003c/li\u003e\n  Memory component is a place where all the variables and keywords are stored as key value pairs.\n  Ex: We have a variable called a equivalent to 10.\n \n  \u003cpre\u003e\u003ccode\u003econst a = 10;\u003c/code\u003e\u003c/pre\u003e\n  \n  \n  \u003ctable align=\"center\" style=\"border:solid black;margin-top:20px\"\u003e\n    \u003ctbody\u003e\u003ctr style=\"border:solid black\"\u003e\n      \u003cth style=\"border:solid black\"\u003eMemory Component\u003c/th\u003e\n      \u003cth style=\"border:solid black\"\u003eCode Component\u003c/th\u003e\n    \u003c/tr\u003e\n    \u003ctr style=\"border:solid black;height:100px\"\u003e\n      \u003ctd style=\"border:solid black\"\u003ea:10\u003c/td\u003e\n      \u003ctd style=\"border:solid black\"\u003eCode execution\u003c/td\u003e\n    \u003c/tr\u003e\n  \u003c/tbody\u003e\u003c/table\u003e\n  \n  \u003cli\u003eCode Component\u003c/li\u003e\n  This is the place where code executed one line at a time.\n  \n  \u003ch2\u003eJavaScript is a synchronous single threaded language.\u003c/h2\u003e\n  \u003cli\u003eSingle Threaded\u003c/li\u003e\n  JavaScript can only execute one command at a time.\n  \u003cli\u003eSynchronous Single threaded\u003c/li\u003e\n  JavaScript can only execute one command at a time and in a specific order. It can only go to the next line once the current line has been finished executing.\n  \n  \u003ch2\u003eWhat happens when you run your JS code\u003c/h2\u003e\n  \u003col\u003e\n    \u003cli\u003eWhen we run a JS program, An execution context will be created\u003c/li\u003e\n    \u003cul\u003e\n      \u003cli\u003eAn execution context is created in two phases.\u003c/li\u003e\n      \u003col\u003e\n        \u003cli\u003eMemory creation phase\u003c/li\u003e\n        In this phase JS will allocate memory to all the variables and functions.\n        \u003cli\u003eCode execution phase\u003c/li\u003e\n        In this phase, Code will be executed after it's memory allocation.\n      \u003c/ol\u003e\n    \u003c/ul\u003e\n  \u003c/ol\u003e\n  \n  Let's Assume we're executing below code\n\n  ```JS\n  var n = 2;\n  function square(num){\n    var ans = num*num;\n    return ans;\n  }\n  \n  var square2 = square(n)\n  var square3 = square(3)\n    \n  ```\n  \n  So as we know first phase is creation-\n  \u003col\u003e\u003cli\u003eMemory Allocation Phase\u003c/li\u003e\n    \u003cul\u003e\n      \u003cli\u003eAllocate memory to n variable\u003c/li\u003e\n      \u003cli\u003eAllocate memory to square function\u003c/li\u003e\n    \u003c/ul\u003e\n    So when JS allocates memory what does it stores?\u003cbr\u003e\n    It stores a special value known as undefined.\n    \u003cbr\u003e But in case of functions, it litterally stores the whole code of the function inside the memory  space.\n    \u003ctable align=\"center\" style=\"border:solid black;margin-top:20px\"\u003e\n    \u003ctbody\u003e\u003ctr style=\"border:solid black\"\u003e\n      \u003cth style=\"border:solid black\"\u003eMemory Component\u003c/th\u003e\n      \u003cth style=\"border:solid black\"\u003eCode Component\u003c/th\u003e\n    \u003c/tr\u003e\n    \u003ctr style=\"border:solid black;height:100px\"\u003e\n      \u003ctd style=\"border:solid black\"\u003e\n        n:undefined\u003cbr\u003e\n        square: {.....}\u003cbr\u003e\n        square2: undefined\u003cbr\u003e\n        square3: undefined\u003cbr\u003e\n      \u003c/td\u003e\n      \u003ctd style=\"border:solid black\"\u003e--------------------------\u003c/td\u003e\n    \u003c/tr\u003e\n  \u003c/tbody\u003e\u003c/table\u003e\n    \u003cli\u003e Code Execution Phase\u003c/li\u003e\n    \u003cul\u003e\n      \u003cli\u003eNow JS once again runs through this whole JavaScript program line by line and it executes the code now.\u003c/li\u003e\n      \u003cli\u003eThis is the point when all these variables, functions, every calculation in the program is done\u003c/li\u003e\n      \u003cli\u003eAs soon as it counters the first line- \u003cbr\u003e\n        var n = 2;\u003cbr\u003eIt actually places the 2 insides then, till now the value of n was undefined now in the second phase of creation of execution context that is the code execution phase in this phase, this 2 value overhere of n is now been placed actually in this placeholder or the identifier which is n.\n      \u003c/li\u003e\n      \u003cli\u003e\n        On line 2 to 5 (function) it sees that here is nothing to execute so it moves to the next line.\n      \u003c/li\u003e\n      \u003cli\u003e\n        In line 6 we are invoking the function.\n        \u003c/li\u003e\u003cli\u003efunctions are like a mini program in JavaScript, whenever a function is invoked, a mini program is invoked so all together a new execution context is created\n      \u003c/li\u003e\n      \u003cli\u003eWhole thing, we were running this whole program was inside the global execution context, now when we run the funtion or when we invoke a function. A brand new context is created.\u003c/li\u003e\n      \u003cli\u003eThen again two phases will be created\n      \u003c/li\u003e\u003cli\u003eMemory creation phase\u003c/li\u003e\n      \u003cli\u003eCode execution phase\u003c/li\u003e\n    \u003c/ul\u003e\n  \u003c/ol\u003e\n  \n\u003ctable\u003e\n    \u003ctbody\u003e\u003ctr \u003e\n      \u003cth \u003eMemory Component\u003c/th\u003e\n      \u003cth\u003eCode Component\u003c/th\u003e\n    \u003c/tr\u003e\n    \u003ctr\u003e\n      \u003ctd\u003e\n        n:2\u003cbr\u003e\n        \u003cbr\u003e\n        square2: 4\u003cbr\u003e\n        square3: 9 \u003cbr\u003e\n      \u003c/td\u003e\n      \u003ctd \u003e\n        \u003ctable \u003e\n    \u003ctbody\u003e\u003ctr \u003e\n      \u003cth \u003eMemory Component\u003c/th\u003e\n      \u003cth\u003eCode Component\u003c/th\u003e\n    \u003c/tr\u003e\n    \u003ctr \u003e\n      \u003ctd \u003e\n        num:2\u003cbr\u003e\n        ans:4\u003cbr\u003e\n      \u003c/td\u003e\n      \u003ctd\u003ereturn ans\u003c/td\u003e\n    \u003c/tr\u003e\n  \u003c/tbody\u003e\u003c/table\u003e\n      \u003c/td\u003e\n    \u003c/tr\u003e\n  \u003c/tbody\u003e\u003c/table\u003e\n  \n\n\u003cbr\u003e\u003cbr\u003e\u003chr\u003e\n\n\u003ch1 id=\"control-flow\" align=center\u003eControlling program logic and flow\u003c/h1\u003e\n\n## Comparison Operators\n```js\n\u003e // greater than\n\u003c // less than\n\u003e= // greater than or equal to\n\u003c= // less than or equal to\n== // equality\n!= // not equal\n=== // strict equality\n!== // strict non-equality\n// these give booleans true or false like this\n5\u003e2 // true\n5\u003c3 //false\n```\n\n### double equals(==)\n\u003cli\u003eChecks for equality of value, but not equality of type.\n\u003cli\u003eIt coerces both values to the same type and then compares them.\n\u003cli\u003eThis can lead to some unexpected results.\n\n### Triple equals(===)\n\u003cli\u003eChecks for equality of value and type.\n\n```js\n7 == '7' // true\n7 ==='7' //false\n```\n\n\u003e Always go with triple equals.\n\n## Making decisions in the code\nA conditional statement can have three pieces-\n\u003cli\u003eIf\n\u003cli\u003eElse if\n\u003cli\u003eElse\n\n### If \nRun code if a given condition is true.\n```js\nlet rate = 3;\nif(rate===3){\n    console.log(\"Amazing\");\n}\n```\n\n### Else If\nif not the first thing, maybe this another thing?\n```js\nlet rate = 2;\nif(rate===3){\n    console.log(\"Amazing\");\n}\nelse if(rate === 2){\n    console.log(\"Oh its ok\");\n}\n```\n\n### Else\nif nothing else was true, do this..\n```js\nlet rate = 349;\nif(rate===3){\n    console.log(\"Amazing\");\n}\nelse if(rate === 2){\n    console.log(\"Oh its ok\");\n}\nelse{\n    console.log(\"Ok we don't know about it\")\n}\n```\n\n### Nesting\nwe can nest conditionals inside conditionals\n```js\nlet password = \"hello kiry\";\nif(password.length \u003e=6){\n    if(password.indexOf(' ')!== -1){\n        console.log(\"Password can't include spaces\");\n    }\n    else{\n        console.log(\"Valid password\")\n    }\n}\nelse{\n    console.log(\"password is too short\");\n}\n```\n\n## Truthy and Falsy values\n\u003cli\u003e All values have an inherent truthy or falsy boolean value\n\u003cli\u003e Falsy values:--\u003cbr\u003efalse\u003cbr\u003e0\u003cbr\u003e\"\"(empty string)\u003cbr\u003enull\u003cbr\u003eundefined\u003cbr\u003eNaN\n\u003cli\u003eEverything else is truthy/\n\n## Logical Operators\n\u003cli\u003eAND(\u0026\u0026)\n\u003cli\u003eOR(||)\n\u003cli\u003eNOT(!)\n\n### AND(\u0026\u0026)\nBoth sides must be true in order for the whole thing to be true\n\n```js\n1\u003c=4 \u0026\u0026 'a'==='a'; // true\n9\u003e10 \u0026\u0026 9\u003e=9 ; // false\n```\n\n### OR(||)\nIf one side is true, the whole thing is true\n\n```js\n// only one side needs to be true\n1!==1 || 10===10 // true\n```\n\n### NOT(!)\nreturns true if the expression is false\n\n```js\n!null // true\n\n!(0===0) // false\n```\n\n## Operator precedence\n\u003cli\u003eNOT(!) has higher precedence than \u0026\u0026 and ||.\n\u003cli\u003e \u0026\u0026 has higher precedence than ||. \u003cbr\u003e\n\n```js\n! \u0026\u0026 ||\n```\nwe can alter these using parentheses.\n\n\n## Switch Statement\n\nThe switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case, as well as statements in cases that follow the matching case.\n\nSyntax---\n\n```js\nswitch (expression) {\n  case value1:\n    //Statements executed when the\n    //result of expression matches value1\n    [break;]\n  case value2:\n    //Statements executed when the\n    //result of expression matches value2\n    [break;]\n  ...\n  case valueN:\n    //Statements executed when the\n    //result of expression matches valueN\n    [break;]\n  [default:\n    //Statements executed when none of\n    //the values match the value of the expression\n    [break;]]\n}\n```\n\n## Ternary Operator\n\n```javascript\ncondition ? expIfTrue: expIfFalse\n```\n\n\n\n## Some questions\n\u003col\u003e\n\u003cli\u003e\u003ca href=\"ifelse/prob1.js\"\u003eProgram to check if a number is even or odd.\u003c/a\u003e\u003c/li\u003e\n\u003cli\u003e\u003ca href=\"ifelse/prob2.js\"\u003eProgram to find maximum, minimum among two numbers\u003c/a\u003e\u003c/li\u003e\n\u003cli\u003e\u003ca href=\"ifelse/prob3.js\"\u003eProgram to find maximum, minimum among three numbers\u003c/a\u003e\u003c/li\u003e\n\u003cli\u003e\u003ca href=\"ifelse/prob4.js\"\u003e Program to check if an alphabet is a vowel or a consonant.\u003c/a\u003e\u003c/li\u003e\n\n\u003c/ol\u003e\n\n\u003ch1 id=\"arrays\"\u003eArrays \u003c/h1\u003e\n\nOrdered collections of values\n\u003cli\u003eList of comments on IG post\n\u003cli\u003eCollection of levels in a game\n\u003cli\u003eSongs in a playlist\u003cbr\u003e\u003cbr\u003e\n\n### Creating arrays\n```js\n// make an empty array\nlet students = [];\n\n// array of strings\nlet names = [\"Rahul\", \"Tushar\", \"Sahul\"];\n\n// an array of numbers\nlet rollNo = [23,45,2,34,6,7]\n\n// mixed array\nlet stuff = [true, 435, 'tushar', null];\n```\n\n#### Arrays are indexed\n```js\nlet colors = ['red','orange','yellow','green']\ncolors.length//4\n\ncolors[0] // 'red'\ncolors[1] // 'orange'\ncolors[2] // 'yellow'\ncolors[3] // 'green'\ncolors[4] // 'undefined'\n```\n### modifying arrays\nunlike strings, arrays are mutable, we can modify arrays\n\n```js\nlet shop = ['milk','sugar'];\nshop[1] = 'coffee';\n// add something at the end\nshop[shop.length] = 'tomatos'\n```\n\n## \u003ca href=\"arrays\"\u003e Array Methods\u003c/a\u003e\n\u003cli\u003e Push - add to end\n\u003cli\u003e Pop - remove from end\n\u003cli\u003e Shift  remove from start\n\u003cli\u003e Unshift - add to start\n\u003cli\u003e________________________________________\n\u003cli\u003e concat - merge arrays\n\u003cli\u003e includes - look for a value, returns true or false\n\u003cli\u003e indexOf - just like str.indexOf\n\u003cli\u003e join - creates a string from arr\n\u003cli\u003e reverse - reverses an array\n\u003cli\u003e slice - copy portion of an arr\n\u003cli\u003e splice - remove/replace elements\n\u003cli\u003e sort - sorts an array.\nThe sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.\u003cbr\u003e\u003cbr\u003e\n\n\u003earrays are reference types which means that the actual array data is not the content that is stored in the slot in memory for each variable.Instead it is a reference.\n\n\u003ewe can modify array elements even it's initialized by const.\n\n\u003ch1 id=\"objects\"\u003eObjects in JavaScript\u003c/h1\u003e\n\nAn object allows us to store data where we can associate things in group pieces of data together but rather than simply ordering data based off of an index to zero with item the first the second like an array does.\n\n\u003cli\u003eObjects are collections of properties.\n\u003cli\u003eProperties are a key value pair.\n\u003cli\u003eRather than accessing data using an index, we use custom keys.\nProperty- key+ value\n\u003cbr\u003e\n\n```js\nconst student = {\n    name: \"Tushar\",\n    rollno: 123,\n    class: 12\n}\n```\n\nin other languages like Python objects are actually\ncalled dictionaries.\n\n## Creating objects literals\nInstead of the square braces that we use for an array we use curly braces to signify an object.\n\n```js\n// accessing properties\nstudent.name // accessing name\n```\n\n\u003ewhen we create an object when we make a property the keys are automatically converted to strings.\n\n```js\nlet num ={\n    34: \"thirty four\"\n}\nnum.34 // throw error because it has converted to a string\n```\n\n### Accessing objects properties\n```js\nconst colors ={\n    red: \"#eb4d4b\",\n    yellow: \"#f9ca24\",\n    blue: \"#30336b\"\n}\ncolors.red\ncolors['blue']\nlet cr = 'yellow';\ncolors[cr] \n\nconst numbers = {\n    100: 'one hundred',\n    16: 'sixteen'\n    '34 thing': \"good\"\n};\nnumbers[100] // 'one hundred'\nnumbers['34 thing']\n```\n\n### Adding and updating properties\n\n```js\nconst users={}\nusers['facebook'] = \"Tushar\";\nusers.insta = \"tush_tr\"; \n```\n\n### Nested arrays and objects\nWe can fill objects with keys that are arrays or also keys that are other objects. And we do this all the time because most of the data we work with in the real world is generally a combination of list or ordered data as well as key value pairs of data.\n\n```js\nconst shopCart = [\n    {\n        product: 'milk',\n        price: 12,\n        quantity: 1\n    },\n    {\n        product: 'water bottle',\n        price: 20,\n        quantity: 5\n    },\n    {\n        product: 'coffee',\n        price: 2,\n        quantity: 20\n    }\n]\n\nconst student = {\n    firstName: 'Tushar',\n    lastName: 'Rajpoot',\n    hobbies: ['Music', 'reading'],\n    marks:{\n        mid: 56,\n        final: 94\n    }\n}\n```\n\nWe know that values in an array are not actually stored in a variable. The variable has limited space available to it. So it stores a reference sort of an address.\u003cbr\u003e\nobjects also work the exact same way.\n\n\u003ewe use const when we want the reference to stay the same like we always want to be pointing to this one object but the contents can come and go.\n\n#### Equality in arrays and objects\nthe value of that variable has the little space in memory is not storing the array it's simply storing\na reference to this array.\n```js\nlet n = [1,2,3];\nlet r = [1,2,3];\nn==r // false\nn===r // false\n// so what we can do \nlet newn = n;\n// now\nnewn===n // true\n```\n if you're trying to compare arrays if you're trying to see if an array is equal to another array it's not as straightforward as you might hope it would be because a lot of times you're not trying to check if an array is the exact same array.\n\n\u003ch1 id=\"loops\"\u003eLoops in JavaScript\u003c/h1\u003e\nDoing things repeatedly.\n\u003cul\u003e\n\u003cli\u003e\nLoops allow us to repeat code\n\u003cli\u003e---Print 'hello' 10 times\u003c/li\u003e\n\u003cli\u003e---Sum all numbers in an array\u003c/li\u003e\n\u003c/li\u003e\n\u003cli\u003e\nThere are multiple types:\n\u003cli\u003e---For loop\u003c/li\u003e\n\u003cli\u003e---While Loop\u003c/li\u003e\n\u003cli\u003e---for....of loop\u003c/li\u003e\n\u003cli\u003e---for....in loop\u003c/li\u003e\n\u003c/li\u003e\n\u003c/ul\u003e\n\n## For Loops\n\n```js\nfor(\n    [initialExpression];\n    [condition];\n    [incrementExpression];\n){}\n// print hello 10 times--\nfor(let i=0;i\u003c=10;i++){\n    console.log('hello');\n}\n```\n\n#### print a multiplication table\n```js\nconst table = (num)=\u003e{\n    for(let i=0;i\u003c=10;i++){\n        console.log(`${num} X ${i} = ${num*i}`);\n    }\n}\ntable(4);\n```\n\n### For loops and arrays\nwe can use for loops to iterate over a string or an array.\n\u003cbr\u003eTo loop over an array, start at 0 and continue to the last index(length-1).\n\n```js\nconst students = ['Ram','Shyam','Mohan'];\nfor(let i=0;i\u003cstudents.length;i++){\n    console.log(i,students[i]);\n}\n// iterating a string\nconst studentName = \"Tushar\";\nfor(let i=studentName.length-1;i\u003e=0;i--){\n    console.log(studentName[i]);\n}\n```\n\n### Nested for loops\nwe can nest loops\n```js\nfor(let i=0;i\u003c=10;i++){\n    console.log(\"Outer loop\",i);\n    for(let j=10;j\u003e=0;j--){\n        console.log(\"Inner loop\",j);\n    }\n}\n// we can use nested loops for iterating 2d arrays\nconst gameBoard = [\n    [4,32,8,4],\n    [64,8,32,2],\n    [8,32,16,4],\n    [2,8,4,2]\n];\nfor(let i=0;i \u003c gameBoard.length;i++){\n    // console.log(gameBoard[i]);\n    for(let j=0;j\u003cgameBoard[i].length;j++)\n    {\n        console.log(gameBoard[i][j]);\n    }\n}\n// output---\n/*\n4\n32\n8\n4\n64\n8\n32\n2\n8\n32\n16\n4\n2\n8\n4\n2\n*/\n```\n\n\n\n## While Loops\nA while loop continues to run as long as its test condition is true.\n```js\nlet n = 0;\nwhile(n\u003c10){\n    console.log(n);\n    n++;\n}\n```\n\n### Break Keyword\nThere is a special keyword in JavaScript called Break which we can use instead of loops to break out of that loop to stop its execution. Whenever javascript encounters break that loop that it's enclosed in is done so you can use this technically in a for loop.\n```js\nfor(let i=0;i\u003c10;i++){\n    console.log(i);\n    if(i===5){\n        break;\n    }\n}\n// in while loops\nwhile(true){ // loop forever\n    if(target === guess){\n        break;\n    }\n}\n```\n### Continue keyword\nfor skipping something\n```js\nfor(let i=0;i\u003c10;i++){\n    if(i===5){\n        continue;\n    }\n    console.log(i)\n}\n```\n\n## For of loop\nA nice and easy way of iterating over arrays(or other iterable objects)[No internet explorer support]\n```js\nfor(variable of iterable){\n    statement\n}\n// example--\nconst arr = [1,2,3,4,5];\nfor(let i of arr){\n    console.log(i);\n}\n// for of with objects\nconst movieRatings ={South: 9.5, BollyWood: 2.5,Hollywood: 9.8};\nObject.keys(movieRatings)\n// \u003e [\"South\", \"BollyWood\", \"Hollywood\"]\nObject.values(movieRatings)\n// \u003e [9.5, 2.5, 9.8]\nfor(let x of Object.keys(movieRatings)){\n    console.log(x)\n}\nfor(let ratings of Object.values(movieRatings)){\n    console.log(ratings);\n}\n```\n\n\u003e We can loop over the keys of an object, using Object.key() and values using Object.values()\n\n## For In Loop\nLoop over the keys in an object\n```js\nfor(variable in object){\n    statement\n}\n// iterate over an object keys\nconst movieRatings ={South: 9.5, BollyWood: 2.5,Hollywood: 9.8};\nfor(let movie in movieRatings){\n    console.log(movie)\n}\n// accessing values with for in loop\nfor(let movie in movieRatings){\n    console.log(movie)\n    console.log(movieRatings[movie])\n}\n```\n\n\u003ch1 id=\"functions\"\u003eFunctions\u003c/h1\u003e\n\nReusable procedures\n\u003cli\u003e Functions allow us to write reusable, modular code.\n\u003cli\u003e We define a 'chunk' of code that we can then execute at a later point.\n\n### Defining functions\n```js\nfunction funcName(){\n    // do something\n}\n// let's write our first function\nfunction hello(){\n    console.log(\"Hello\")\n}\n```\n\n### function arguments\n\nwe can also write functions that accept inputs, called arguments.\n\n```js\nfunction greet(person){\n    console.log(`hello ${person}`)\n}\nfunction add(a,b){\n    console.log(a+b);\n}\n```\n\n### Return statement\nbuilt-in methods return values when we call them. We can store those values:\n\n```js\nfunction add(x,y){\n    return x+y;\n}\nconsole.log(add(2,3));\n// we can capture a return value in a variable.\nlet a = add(2,3)\n```\n\n#### No return\nour functions print values out, but don't return anything.\n```js\nfunction add(x,y){\n    console.log(x+y)\n}\nadd(3,3);\n```\n\n\n\n\n\n\u003ch1 id=\"scope\"\u003eOther Important concepts about functions\u003c/h1\u003e\n\n### What is scope?\n\n\u003e Variable \"visibility\"\n\n\u003cli\u003eThe location where a variable is defined dictates where we have access to that variable.\n\n### Function Scope\n\n```js\nfunction show(){\n    let msg = \"Hey I'm here\";\n    // msg is scoped to the show function\n}\n// we can't access or manipulate msg variable outside of this function.\n```\n\n### Block Scope\n\n```js\nlet rad = 8;\nif(rad\u003e0){\n    var a = 12;\n    const PI  = 3.14;\n    let area = 2*PI*rad;\n}\nconsole.log(rad) // 8\nconsole.log(area) // undefined\nconsole.log(a) // 12\n// this tells us that let and const have\n// different scoping rules than var\n// there was one more problem with var\nlet arr = [1,2,3,4];\nfor(var i=0;i\u003carr.length;i++){\n    console.log(i,arr[i]);\n}\nconsole.log(i) // 3\n```\n\n### Lexical Scope\n```js\nfunction outer(){\n    let hero = \"Black Panther\";\n    function inner(){\n        let cryForHelp = `${hero}, please save me! `;\n        console.log(cryForHelp);\n    }\n    inner();\n}\n```\n\n## Function Expressions\nthere's another syntax we can use to define functions:\n```js\nconst square = function(num){\n    return num*num;\n}\nsquare(7); // 49\n```\n\nThe main distinction here is that the function does not actually have a name. It's stored in a variable but we haven't provided a name.\n\n## Higher Order Functions\n\u003e Functions are objects\nWe can put functions in an array.\u003cbr\u003e\nWe can also put a function in an object.\n\n### Functions as arguments\npassing functions as an argument to another function or returning a function which is actually a very key part of javascript.\n\u003cbr\u003e\n\n#### What are higher order functions?\nFunctions that operate on/with other functions. They can:\n\u003cli\u003eAccept other functions as arguments\n\u003cli\u003eReturn a function\n\n```js\nfunction callTwice(func){\n    func();\n    func();\n}\n\nfunction laugh(){\n    console.log(\"hahahahahhah\");\n}\n\ncallTwice(laugh);\n```\n\n### Returning functions\n```js\nfunction makeBetweenFunc(min,max){\n    return function (val){\n        return val\u003e=min \u0026\u0026 val\u003c=max;\n    }\n}\nconst inAgeRange = makeBetweenFunc(18,100);\nconsole.log(inAgeRange(45)) // true\n```\n\n## Callback Functions\nA callback function is a function passed into another function as an argument, which is then  invoked inside the outer function.\n\n```js\nfunction callTwice(func){\n    func();\n    func();\n}\nfunction laugh(){\n    console.log(\"hahahahha\");\n}\ncallTwice(laugh) // pass a function as argument\n// so here laugh is a callback function\n// we can also do the same like this\ncallTwice(function (){\n    console.log(\"Calling again\");\n})\n```\n\nWe can write our own function that accepts callbacks but also tons of the built in methods, that are really useful ones in JavaScript expect you to pass in a callback.\nif you want to make a request to load data from Facebook API. That request takes time. We pass in a callback function that will be called when the request is finished. When the data is back if we want to run code when a user clicks on a button on a page or when they hover over a photo the code that we write to set that up requires us to pass in a callback function which will be executed when the user hovers or when the user clicks.\n\n#### Anonymous functions\nwe use anonymous functions when we call callback functions(higher order functions). We pass in an anonymous function rather than an existing function like laugh.\n\nThere's nothing wrong with this\n```js\ncallTwice(laugh)\n```\nbut sometimes we just need a one time use function. We don't need it to be a standalone function in which case we use an anonymous function.\n\n### setTimeout function\nThere is a method called set timeout set timeout will run a certain block of code or a function of code after a certain number of milliseconds or seconds we pass in a number of milliseconds like five thousand which is five seconds but the first argument we need to pass it is a function so a function to run and then how long to wait before it runs.\n\n```js\nfunction notice(){\n    alert(\"go away\");\n}\nsetTimeout(notice,5000);\n// this will wait till 5 second then execute notice function\n// so we don't to define a function always we can use anonymous function like this\nsetTimeout(function(){\n    alert(\"Go away\");\n},5000);\n```\n\n## Hoisting\n\n\u003eHoisting is JavaScript's default behavior of moving declarations to the top.\n\nRemember that variables when we declare them but don't initialize them. For example var x and I don't give it a value, X is set to undefined.\n```js\nlet x;\n\u003eundefined\n```\n\nso when you execute a js program, it hoists up all variable declaration. for ex, if you try to run this code\n```js\nconsole.log(student); // undefined\nvar student = \"Tushar\"\n```\nWhen javascript is interpreting the code what happens is that it hoists up I'm doing air quotes but\nyou can't see it. It hoist up the variable declaration.(var student)\n\n#### With let and const-\nVariables defined with let and const are hoisted to the top of the block, but not initialized.\nMeaning: The block of code is aware of the variable, but it cannot be used until it has been declared.\n\nUsing a let variable before it is declared will result in a ReferenceError.\n\n\u003ewhen you declare variable with let it's not hoisted.\n\n\nUsing a const variable before it is declared, is a syntax errror, so the code will simply not run.\n\n\u003e Let and const are not hoisted\n\n#### Functions are hoisted\n```js\nshow();\nfunction show(){\n    console.log(\"helooooo\");\n}\n```\n\nBut But if we use function expression, it not gonna work\n```js\nconsole.log(show) // undefined because its a variable that has been declared\nshow(); // error\nvar show = function(){\n    console.log(\"Hloooo\")\n}\n// but if we declare this function using let or const it will not work.\n```\n\n\u003ch1 id=\"arraymethods\"\u003eArray callback methods\u003c/h1\u003e\n\n\u003cli\u003eArrays come with many built-in methods that accept callback functions.\n\n## For Each \naccepts a callback function.\nCalls the function once per element in the array.\n\n```js\nconst num = [1,2,3,4,5,6];\nnum.forEach(function(n){ // n parameter represents one element at a time\n    console.log(n)\n})\n```\nWe can also add a second parameter to our callback to the function here if we want to use the index.\n```js\nnum.forEach(function(e,i){\n    console.log(i,e);\n})\n```\n\n## Map Method\ncreates a new array with the results of calling a callback on every element in the array\n\n```js\nconst texts = ['fer','rrer','rer','erre'];\nconst caps = texts.map(function(t){\n    return t.toUpperCase();\n})\n```\n\n## Arrow Functions\nSyntactically compact alternative to a regular function expression.\n```js\nconst square = (x)=\u003e{\n    return x*x;\n}\n```\n\n### Implicit return\nall these functions do the same thing:\n```js\nconst isEven = function(num){\n    return num%2===0;\n}\nconst isEven = (num)=\u003e{\n    return num%2===0;\n}\nconst isEven = num =\u003e{\n    return num%2===0;\n}\nconst isEven = num =\u003e{ // implicit return\n    num%2===0\n} \nconst isEven = num=\u003e num%2===0;// one-liner implicit return\n```\n\n## Find method\nreturns the value of the first element in the array that satisfies the provided testing function.\n\n```js\nlet shoppingList = [\n    \"Veggies\",\n    \"Milk\",\n    \"Notebooks\"\n]\nlet item = shoppingList.find(item=\u003e{\n    return item.includes(\"Milk\");\n})\n```\n\n## Filter method\ncreates a new array with all elements that pass the test implemented by the provided function.\n```js\nconst numbers = [12,334,542,3,34,54,5,45,3,4,523,6,3]\nconst evens = numbers.filter(n=\u003e{\n    return n%2===0;\n})\n```\n\n## Every and Some method\n#### Every-\ntests whether all elements in the array pass the provided function It returns a boolean value.\n```js\nconst words = ['dog','dog','dig','dag','bag'];\nwords.every(word=\u003e{\n    return word.length === 3;\n}) // true\n```\n\n#### Some -\nSimilar to every, but returns true if any of the array elements pass the test function.\n```js\nwords.some(word=\u003e{\n    return word.length \u003e4;\n})\n```\n\n## Sort\n\u003cpre\u003e\narr.sort(compareFunc(a,b)))\n\u003c/pre\u003e\n\u003cli\u003eIf compareFunc(a,b) returns less than 0 \n-\u003e Sort a before b\n\u003cli\u003eIf compareFunc(a,b) returns 0\n-\u003e leave a and b unchanged with respect to each other\n\u003cli\u003eIf compareFunc(a,b) returns greater than 0\n-\u003e Sort b before a\n\n\n\n```js\nconst prices = [122,4542,453,5248,78709,3435];\nprices.sort(); // it's weird converts into strings then sort\n\nprices.sort((a,b)=\u003e a-b);\n\nprices.sort((a,b)=\u003eb-a);\n\n```\n\n## Reduce Method\nexecutes a reducer function on each element of the array, resulting in a single value.\n\n#### Summing an array\n```js\nconst arr = [3,5,7,9,11];\narr.reduce((accumulator, currentValue)=\u003e{\n    return accumulator+currentValue;\n})\n```\n\n\u003ctable\u003e\n\u003ctr\u003e\n\u003ctd\u003eCallback\u003c/td\u003e\n\u003ctd\u003eAccumulator\u003c/td\u003e\n\u003ctd\u003eCurrentvalue\u003c/td\u003e\n\u003ctd\u003ereturn value\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003efirst call\u003c/td\u003e\n\u003ctd\u003e3\u003c/td\u003e\n\u003ctd\u003e5\u003c/td\u003e\n\u003ctd\u003e8\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003esecond call\u003c/td\u003e\n\u003ctd\u003e8\u003c/td\u003e\n\u003ctd\u003e7\u003c/td\u003e\n\u003ctd\u003e15\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003ethird call\u003c/td\u003e\n\u003ctd\u003e15\u003c/td\u003e\n\u003ctd\u003e9\u003c/td\u003e\n\u003ctd\u003e24\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003efourth call\u003c/td\u003e\n\u003ctd\u003e24\u003c/td\u003e\n\u003ctd\u003e11\u003c/td\u003e\n\u003ctd\u003e35\u003c/td\u003e\n\u003c/tr\u003e\n\u003c/table\u003e\n\n\nit's not always about summing or multiplying or accumulating data in one number. It could be finding the maximum value in an entire array.\n\n#### Initial value\nwhen you use reduce you can actually pass in an initial starting value. So after your callback the format would be something dot reduce.\n```js\n[12,23,5,6].reduce((acc,curr)=\u003e{\n    return acc+curr;\n},100)\n```\n\n#### Tallying\nwe can tally up results from an array we can group different values in an array using an object.\n```js\nconst vote = ['y','y','n','y','y','y','n']\nconst tally = vote.reduce((tally, vote)=\u003e{\n    tally[vote] = (tally[vote] || 0)+1\n    return tally;\n},{})\n// {}- initial object\n```\n\u003ch1 id=\"more-js\"\u003eDefault Parameters, Spreads,Rest Parameters, Destructuring\u003c/h1\u003e\n\nlist of some important JS new features\n\u003ctable\u003e\n\u003ctr\u003e\n\u003ctd\u003eArrow functions\u003c/td\u003e\n\u003ctd\u003eString template literals\u003c/td\u003e\n\u003ctd\u003eLet and const\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003eFor...of\u003c/td\u003e\n\u003ctd\u003efor...in\u003c/td\u003e\n\u003ctd\u003eExponent operator\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003eString.includes()\u003c/td\u003e\n\u003ctd\u003eArray.includes()\u003c/td\u003e\n\u003ctd\u003eObject.values()\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003eRest \u0026 Spread\u003c/td\u003e\n\u003ctd\u003eDestructuring\u003c/td\u003e\n\u003ctd\u003eDefault function params\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003eObject Enhancements\u003c/td\u003e\n\u003ctd\u003eClasses\u003c/td\u003e\n\u003ctd\u003eAsync Functions\u003c/td\u003e\n\u003c/tr\u003e\u003c/table\u003e\n\n## Default parameter\n```js\nfunction multiply(a,b=1){\n    //means if no b is passed in if it's undefined.  Use this value.\n    return a*b;\n}\nmultiply(4); // 4\nmultiply(4,3); // 12\n```\n\n## Spread\nIt does many things.\n\u003cbr\u003e\nSpread syntax allows an iterable such as an array to be expanded in places where zero or more arguments(for function calls) or elements(for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs(for object literals) are expected.\n\n```js\nfunction sum(x, y, z) {\n  return x + y + z;\n}\n\nconst numbers = [1, 2, 3];\n\nconsole.log(sum(...numbers));\n// expected output: 6\nconsole.log(sum.apply(null, numbers));\n// expected output: 6\n```\n\n### Spread in array literals\nIn array literals -\n\u003cbr\u003e\nCreate a new array using an existing array. Spreads the elements from one array into a new array.\n\n```js\nconst n1 = [1,2,3];\nconst n2 = [4,5,6];\n[...n1,...n2];\n// [1,2,3,4,5,6]\n\n['a','b',...n2];\n// [\"a\",\"b\",4,5,6]\n\nconst a = [1,2,3]\nconst b = [23]\nb.push(...a)\nconsole.log(b)\n// [23, 1, 2, 3]\n```\n\n#### In object literals\ncopies properties from one object into another object literal.\n\n```js\nconst dog = {name: \"Joolie\",age:6};\nconst animal = {...dog, isPet: true};\n// {name: \"Joolie\",age:6,isPet: true}\n```\n\n## The arguments object\n\u003cli\u003eAvailable inside every function\n\u003cli\u003eIt's like an array-like object\n\u003cbr\u003eHas a length  property\n\u003cbr\u003eDoes not have array methods like push/pop\n\u003cli\u003eContains all the arguments passed to the function\n\u003cli\u003eNot available inside of arrow functions\n\n```js\nfunction sumAll(){\n    let total = 0;\n    for(let i=0; i\u003c arguments.length; i++){\n        total += arguments[i];\n    }\n    return total;\n}\nsumAll(8,3,4,5);\n```\n\n## Rest (...) Params\ncollects all remaining arguments into an actual array.\n\n```js\nfunction sum(...numbers){\n    return nums.reduce((t,c)=\u003e{\n        return t+c;\n    })\n}\n// we can use this in arrow function\nconst fullName = (firstName, secondName, ...titles)=\u003e{\n    console.log('first',firstName)\n    console.log('second',secondName)\n    console.log('titles',titles)\n}\n```\n\n\n## Destructuring\nA short, clean syntax to 'unpack':\n\u003cli\u003e values from arrays\n\u003cli\u003e Properties from objects\nInto distinct variables.\n\n### Destructuring arrays\n```js\nconst arr = [223,535,536];\nconst [one,two,three] = arr;\none// 223\ntwo // 535\nthree // 536\n\nconst [one, ...everyElse] = arr;\none // 223\neveryElse // [535,536]\n```\n\n### Destructuring objects\n```js\nconst runner = {\n    first :  \"Eliud\",\n    last: \"Kipchoge\",\n    country: \"Kenya\",\n    title: \"Elder of the order of the golden heart of kenya\"\n}\n\nconst {first, last, country} = runner;\nfirst // \"Eliud\"\nlast // \"Kipchoge\"\ncountry // \"Kenya\"\n\nconst {country: nation} = runner;\nnation // \"Kenya\"\n```\n\n### Parameters destructuring\n```js\nconst fullName = ({first,last})=\u003e{\n    return `${first} ${last}`\n}\nconst runner = {\n    first :  \"Eliud\",\n    last: \"Kipchoge\",\n    country: \"Kenya\",\n    title: \"Elder of the order of the golden heart of kenya\"\n}\nfullName(runner); // Eliud Kipchoge\n```\n\n\u003ch1 id=\"objectmethods\"\u003eObject Methods and the \"This\" Keyword\u003c/h1\u003e\n\n### Short hand properties\n```js\nconst a = 12;\nconst t = \"Tushar\";\nconst n = {a,t};\nconsole.log(n)\n// {a: 12, t: \"Tushar\"}\n```\n\n### Computed Properties\nwe can use a variable as a key name in an object literal property.\n```js\nconst role = 'SDE';\nconst person = \"Tushar\";\nconst role2 = 'Sys Admin';\nconst person2 = 'Navneet';\n\nconst team = {};\nteam[role] = person;\nteam[role2] =  person2;\n// or\nconst team = {\n    [role]: person,\n    [role2]: person2,\n    [23+34]: 'Another'\n}\n\nconst addProp = (obj,k,v)=\u003e{\n    return{\n        ...obj,\n        [k]:v\n    }\n}\n```\n\n## Methods\nWe can add functions as properties on objects.\n\nwe call them methods.\n\n```js\nconst math ={\n    multiply: function(x,y){\n        return x*y;\n    },\n    divide: function(x,y){\n        return x/y;\n    }\n}\n```\n\n### Method short hand syntax\nwe do this so often that there's a new shorthand way ofadding methods.\n\n```js\nconst math = {\n    msg: \"Hii this is math\",\n    add(x,y){\n        return x+y;\n    }\n    multiply(x,y){\n        return x*y\n    }\n}\n\nmath.add(40,50) // 90\n```\n\n## This keyword\nThe JavaScript this keyword refers to the object it belongs to. It has different values depending on where it is used: ... In a function, this refers to the global object. \n\n\nIt has different values depending on where it is used:\n\u003cli\u003eIn a method, this refers to the owner object.\n\u003cli\u003eAlone, this refers to the global object.\n\u003cli\u003eIn a function, this refers to the global object.\n\u003cli\u003eIn a function, in strict mode, this is undefined.\n\u003cli\u003eIn an event, this refers to the element that received the event.\n\u003cli\u003eMethods like call(), and apply() can refer this to any object.\n\n\u003eThe value of this depends on the invocation context the unction it is used in.\n\n```js\nconst person = {\n    first: \"Tushar\",\n    last : \"Rajpoot\",\n    nickName: false,\n    fullName(){\n        // console.log(this)\n        return `${this.first} ${this.last}`\n    },\n    printBio(){\n        const fullName = this.fullName();\n        console.log(`${fullName} is a person`)\n    }\n}\n```\n\u003e We should not use arrow functions in methods\n\n\n\u003ch1 id=\"dom\" align=center\u003e Document Object Model\u003c/h1\u003e\n\u003cli\u003eThe DOM is a JavaScript representation of a webpage.\n\u003cli\u003eIt's your JS \"window\" into the contents of a webpage\n\u003cli\u003eIt's just a bunch of objects that you can interact with via JS.\n\n### The Document Object\nThe document object is our entry point into the world of the DOM. It contains representations of all the content on a page, plus tons of useful methods and properties.\n\n### Selecting\n\u003cli\u003egetElementById\n\u003cli\u003egetElementsByTagName\n\u003cli\u003egetElementsByClassName\n\n#### querySelector\n\u003cli\u003eA newer, all-in-one method to select a single element.\n\u003cli\u003ePass in a CSS selector\n\n```js\nconst btn = document.querySelector(\".red\")\n```\n\n\n#### querySelectorAll\nSame idea but it selects a collection of elements.\n\n```js\nconst buttons = document.querySelector(\".red\")\n```\n\n### properties and methods\n\n\u003cli\u003eclassList\n\u003cli\u003egetAttribute()\n\u003cli\u003esetAttribute()\n\u003cli\u003eappendChild()\n\u003cli\u003eappend()\n\u003cli\u003eprepend()\n\u003cli\u003eremoveChild()\n\u003cli\u003eremove()\n\u003cli\u003ecreateElement\n\u003cli\u003einnerText\n\u003cli\u003etextContent\n\u003cli\u003einnerHTML\n\u003cli\u003evalue\n\u003cli\u003eparentElement\n\u003cli\u003echildren\n\u003cli\u003enextSibling\n\u003cli\u003epreviousSibling\n\u003cli\u003estyle\n\n### Events in DOM\nResponding to user inputs and actions !\n\n\u003cli\u003eclicks\n\u003cli\u003edrags\n\u003cli\u003edrops\n\u003cli\u003ehovers\n\u003cli\u003escrolls\n\u003cli\u003eform submission\n\u003cli\u003ekey presses\n\u003cli\u003efocus/blur\n\u003cli\u003emouse wheel\n\u003cli\u003edouble click\n\u003cli\u003ecopying\n\u003cli\u003epasting\n\u003cli\u003eaudio start\n\u003cli\u003escreen resize\n\u003cli\u003eprinting\n\n\n### addEventListener\nSpecify the event type and a callback to run.\n\n```js\nconst button = document.querySelector(\"h1\");\nbutton.addEventListener(\"click\",()=\u003e{\n    alert(\"You clicked me\")\n})\n```\n\n\n### getAttribute() and setAttribute()\n\n```js\nconst btn = document.querySelector('input[type=\"submit\"]')\n\nbtn.getAttribute('type')\n\u003e\"submit\"\nbtn.setAttribute('type','new')\n```\n\n### finding parent/children/sibling\n\n```js\nelement.parentElement\nelement.children\nelement.nextSibling\nelement.previousSibling\n```\n\n### changing multiple elements\n\n```js\nconst buttons = document.querySelectorAll('.btn')\nbuttons.forEach((e)=\u003e{\n    e.innerText = 'new Button'\n})\n```\n\n### Altering styles\nevery element has a style property.\n\nwe can use the style property to change colors or styles we can change any of those properties and they will be affected on the page but if we're trying to use the style property to read existing properties to read existing styles it won't work unless those styles are defined inline.\n\n#### getComputedStyle\n```js\nlet styles = getComputedStyle(h1)\n```\n\n### Manipulating classes\n\n```js\ntodo.setAttribute(\"class\",\"done\")\n// remove a class\ntodo.classList.remove('done')\n// add a class\ntodo.classlist.add('done')\n// check element has class or not\ntodoAdd.getAttribute('class').includes('done')\n// toggle will remove if class exist and add class if it doesn't'\ntodoAdd.classList.toggle('done')\n```\n\n\n### Creating elements\n\n```js\nlet h1 = document.createElement('h1')\nh1.innerText = \"This is heading 1\"\n// add class to the element\nh1.classList.add('heading')\n// add an id to the element\nh1.setAttribute('id','heading1')\n\n// add an element to the existing element\nconst section = document.querySelector('section')\nconst newImg = document.createElement('img')\nnewImg.setAttribute('src',url)\nsection.appendChild(newImg)\n```\n\n### append, prepend and insertBefore\n\n```js\nconst parentUl = document.querySelector('ul')\nconst newLi = document.createElement('li')\nnewLi.innerText = \"Tushar\"\nparentUl.appendChild(newLi)\nconst firstLi = document.querySelector('li')​\nparentUl.insertBefore(newLi,firstLi)\n```\n\n#### insertAdjacentElement\n\n\n```js\nelement.insertAdjacentHTML(position, text);\n```\n\n\u003e'beforebegin': Before the element itself.\n\u003e'afterbegin': Just inside the element, before its first child.\n\u003e'beforeend': Just inside the element, after its last child.\n\u003e'afterend': After the element itself.\n\n```HTML\n\u003c!-- beforebegin --\u003e\n\u003cp\u003e\n  \u003c!-- afterbegin --\u003e\n  foo\n  \u003c!-- beforeend --\u003e\n\u003c/p\u003e\n\u003c!-- afterend --\u003e\n```\n```js\nconst le = document.createElement('li')\nh1.insertAdjacentElement('beforebegin',le)\n```\n\n#### append()\n```js\nfirstP.append(i,newLi);\nfirstP.prepend(i,newLi)\n```\n\n#### removeChild()\n```js\nconst ul = document.querySelector('ul')​\nconst removeMe = ul.querySelector('.special')​\nul.removeChild(removeMe)\n```\n\n#### remove()\n\u003e doesn't need parent element\n\n```js\nremoveMe.remove()\n```\n\n\u003ch1 id=\"events\"\u003e DOM Events\u003c/h1\u003e\n\n#### Responding to user inputs and actions.\n\n\u003cli\u003eclicks\n\u003cli\u003edrags\n\u003cli\u003edrops\n\u003cli\u003ehovers\n\u003cli\u003escrolls\n\u003cli\u003eform submission\n\u003cli\u003ekey presses\n\u003cli\u003efocus/blur\n\u003cli\u003emouse wheel\n\u003cli\u003edouble click\n\u003cli\u003ecopying\n\u003cli\u003epasting\n\u003cli\u003eaudio start\n\u003cli\u003escreen resize\n\u003cli\u003eprinting\n\n## Using Events\n### using on\n```HTML\n\u003cbutton onclick=\"fun()\"\u003eClick\u003c/button\u003e\n```\n\u003eMore content will be added soon for events\n\u003chr\u003e\n\n\n\n\u003ch1 id=\"async\" align=center\u003eAsynchronous JavaScript, Callbacks and Promises\u003c/h1\u003e\n\n## Call Stack\nThe mechanism the JS interpreter uses to keep track of its place in a script that calls multiple functions.\n\nHow JS \"knows\" what function is currently being run and what functions are called from within that function etc.\n\n### How it works\n\n\u003cli\u003e When a script calls a function, the interpreter adds it to the call stack and then starts carrying out the function.\n\n\u003cli\u003eAny functions that are called by that function are added the call stack further up, and run where their callls are reached\n\n\u003cli\u003eWhen the current function is finished, the interpreter takes it off the stack and resumes execution where it left off the last code listing.\n\n\u003eStack is a linear data structure which follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). There are many real-life examples of a stack\n\n```js\nconst multiply = (x,y) =\u003e x*y;\nconst square = (x) =\u003e multiply(x,x);\n\nconst isRightTriangle = (a,b,c)=\u003e{\n    return square(a) + square(b)=== square(c);\n}\n\nisRightTriangle(3,4,5);\n// square(3) + square(4)===square(4)\n\n```\n\n## JavaScript is a single threaded language\nAt any given point in time, that single JS thread is running at most one line of JS code.\n\n\n## How asynchronous callbacks actually work?\n\n\u003cli\u003eBrowsers come with web APIs that are able to handle certain tasks in the background (like making requests or setTimeout)                   \n\u003cli\u003eThe JS call stack regocnizes these web API functions and passes them off to the browser to take care of\n\u003cli\u003eOnce the browser finishes those tasks, they return and are pushed onto the stack as a callback.\n\ntry your code here :- \u003ca href=\"http://latentflip.com/loupe/?code=JC5vbignYnV0dG9uJywgJ2NsaWNrJywgZnVuY3Rpb24gb25DbGljaygpIHsKICAgIHNldFRpbWVvdXQoZnVuY3Rpb24gdGltZXIoKSB7CiAgICAgICAgY29uc29sZS5sb2coJ1lvdSBjbGlja2VkIHRoZSBidXR0b24hJyk7ICAgIAogICAgfSwgMjAwMCk7Cn0pOwoKY29uc29sZS5sb2coIkhpISIpOwoKc2V0VGltZW91dChmdW5jdGlvbiB0aW1lb3V0KCkgewogICAgY29uc29sZS5sb2coIkNsaWNrIHRoZSBidXR0b24hIik7Cn0sIDUwMDApOwoKY29uc29sZS5sb2coIldlbGNvbWUgdG8gbG91cGUuIik7!!!PGJ1dHRvbj5DbGljayBtZSE8L2J1dHRvbj4%3D\"\u003eclick here\u003c/a\u003e\n\n\n## Callback Hell\n\n### What is Synchronous Javascript?\nIn Synchronous Javascript, when we run the code, the result is returned as soon as the browser can do. Only one operation can happen at a time because it is single-threaded. So, all other processes are put on hold while an operation is executing.\n\n### What is Asynchronous Javascript?\n\n\u003cli\u003eSome functions in Javascript requires AJAX because the response from some functions are not immediate. It takes some time and the next operation cannot start immediately. It has to wait for the function to finish in the background. In such cases, the callbacks need to be asynchronous.\n\u003cli\u003eThere are some external Javascript Web APIs that allows AJAX – Asynchronous Javascript and XML.\nIn AJAX, many operations can be performed simultaneously.\n\n### What is a callback?\n\n\u003cli\u003eCallbacks are nothing but functions that take some time to produce a result.\n\u003cli\u003eUsually these async callbacks (async short for asynchronous) are used for accessing values from databases, downloading images, reading files etc.\n\u003cli\u003eAs these take time to finish, we can neither proceed to next line because it might throw an error saying unavailable nor we can pause our program.\n\u003cli\u003eSo we need to store the result and call back when it is complete.\n\n### What is callback hell?\nThis is a big issue caused by coding with complex nested callbacks. Here, each and every callback takes an argument that is a result of the previous callbacks. In this manner, The code structure looks like a pyramid, making it difficult to read and maintain. Also, if there is an error in one function, then all other functions get affected.\n\n# Promises\nA promise is an object representing the eventual completion or failure of an asynchronous operation. \n\n\u003e A Pattren for writing async code. \n\nA promise is a returned object to which we can attach callbacks, instead of passing callbacks into a function.\n\nwhen we create a promise, we pass in a function. And this function has two parameters. Always these two parameters we usually call resolve and reject. And these are actually functions. \n\nInside of inside promise function if we call resolve, the promise will be resolved. If we call reject, the promise will be rejected.\n\n\u003cli\u003eIf we don't resolve or reject it, it's status will be pending.\n\u003cli\u003eIf we reject it, our promise status will be rejected.\n\u003cli\u003eIf we resolve it, promise status will be resolved. \n\n\n\n```js\n// create a promise which resolved using a random number\nconst getMePhone = new Promise((resolve,reject) =\u003e {\n    let rand = Math.random()\n    if(rand\u003c0.5){\n        resolve()\n    }\n    else{\n        reject()\n    }\n\n})\n```\n\n#### How do I run code if this promise was rejected versus run code, if this promise was resolved?\n\u003cb\u003e.then:\u003c/b\u003e every promise has a then method. this then method will run if our promise is resolved.\n\n\u003cb\u003e.catch\u003c/b\u003e Every promise has a catch method also. We can chain it with .then or we can write along with promise.\n\n```js\ngetMePhone.then(()=\u003e{\n    console.log(\"Yeah I got a Phone\")\n}).catch(()=\u003e{\n    console.log(\"No Phone\")\n})\n```\n\n\n\n## Returning promises from Functions\n\n```js\n// returning a promise from a function\nconst makeDogPromise = () =\u003e {\n    return new Promise((resolve, reject) =\u003e {\n        setTimeout(() =\u003e {\n            const rand = Math.random();\n            if (rand \u003c 0.5) {\n                resolve()\n            }\n            else\n                reject()\n        }, 5000)\n    })\n}\nmakeDogPromise().then(()=\u003e{\n    console.log(\"hello\")\n})\n```\n\n## Resolving/rejecting promises with values\nwe can pass information in to the resolve or reject calls.\n```js\nconst fakeRequest = (url)=\u003e{\n    return new Promise((resolve,reject)=\u003e{\n        setTimeout(()=\u003e{\n            const pages = {\n                '/users' : \"Users pages\",\n                '/about' : \"About page\"\n            }\n            const data = pages[url]\n            if(data){                \n\n                resolve(pages[url])\n            }\n            else{\n                reject({status:400})\n            }\n        },2000)\n    })\n}\n\nfakeRequest('/users').then((data)=\u003e{\n    console.log(data)\n}).catch((res)=\u003e{console.log(res.status)})\n```\n\n## Promise Chaining\n```js\nconst fakeRequest = (url) =\u003e {\n    return new Promise((resolve, reject) =\u003e {\n        setTimeout(() =\u003e {\n            const pages = {\n                '/users': [\n                    { id: 1, username: 'Tushar' },\n                    { id: 5, username: 'Rahul' }\n                ],\n                '/users/1': {\n                    id: 1,\n                    username: 'Tushar',\n                    country: 'India',\n                    work: 'Noida',\n                    role: 'Software Engineer',\n                    postid: 54\n                },\n                '/users/5': {\n                    id: 5,\n                    username: 'Rahul',\n                    country: 'India',\n                    work: 'Noida',\n                    role: 'DevOps Engineer'\n                },\n                '/posts/54': {\n                    id: 54,\n                    title: 'My new Post',\n\n                },\n                '/about': \"About page\"\n            }\n\n            const data = pages[url]\n            if (data) {\n                resolve(pages[url])\n            }\n            else {\n                reject({ status: 400 })\n            }\n        }, 2000)\n    })\n}\n\nfakeRequest('/users').then((data) =\u003e {\n    let id = data[0].id;\n    return fakeRequest(`/users/${id}`)\n})\n    .then((data) =\u003e {\n        // console.log(data)\n        let postid = data.postid;\n        return fakeRequest(`/posts/${postid}`)\n    })\n    .then((data) =\u003e {\n        console.log(data)\n    })\n    .catch((err) =\u003e { console.log(err) })\n```\n\n\u003chr\u003e\n\n\u003ch1 id=\"making-requests\" align=center\u003eMaking http requests\u003c/h1\u003e\n\n\u003cli\u003eXMLHTTP (old standard method)\n\u003cli\u003eFetch (a better way)\n\u003cli\u003eAxios (a third party library)\n\n## What is AJAX?\nAsynchronous Javascript and XML.\u003cbr\u003e\nAJAX is a technique for accessing web servers from a web page.\n\u003cli\u003eRead data from a web server - after a web page has loaded\n\u003cli\u003eUpdate a web page without reloading the page\n\u003cli\u003eSend data to a web server - in the background\n\n### AJAX just uses a combination of:\u003cbr\u003e\nA browser built-in XMLHttpRequest object (to request data from a web server)\nJavaScript and HTML DOM (to display or use the data)\n\n\nAJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.\n\n\u003cimg src=\"https://www.w3schools.com/whatis/img_ajax.gif\"\u003e\n\n1. An event occurs in a web page (the page is loaded, a button is clicked)\n2. An XMLHttpRequest object is created by JavaScript\n3. The XMLHttpRequest object sends a request to a web server\n4. The server processes the request\n5. The server sends a response back to the web page\n6. The response is read by JavaScript\n7. Proper action (like page update) is performed by JavaScript\n\n## XML and JSON \nAJAJ- Asyncrhonous Javascript and JSON .\n\nXML and JSON are two ways of basically formatting data so that you can send it from a server to another server or a server to a browser.\n\n### XML Format\n\n```XML\n\u003cnote\u003e\n\u003cto\u003eTove\u003c/to\u003e\n\u003cfrom\u003eJani\u003c/from\u003e\n\u003cheading\u003eReminder\u003c/heading\u003e\n\u003cbody\u003eDon't forget me this weekend!\u003c/body\u003e\n\u003c/note\u003e\n```\n\n### JSON Format\n(JavaScript Object Notation)\n\n```JSON\n{  \n    \"employee\": {  \n        \"name\":       \"sonoo\",   \n        \"salary\":      56000,   \n        \"married\":    true  \n    }  \n}  \n```\n\n\u003cli\u003eJSON is not JS object\n\u003cli\u003eEvery key in JSON must be a string \n\u003cli\u003eWe can also use arrays in JSON \n\u003cli\u003eWe can easily translate between JSON to JavaScript\n\n## XMLHttpRequest \n\u003cli\u003eThe \"original\" way of sending requests via JS.\n\u003cli\u003eDoes not support promises, so... lots of callbacks\n\u003cli\u003eWTF is going on with the weird capitalization\n\u003cli\u003eClunky syntax that I find difficult to remember.\n\n```js\nconst myReq = new XMLHttpRequest();\nmyReq.onload = function(){\n    const data = JSON.parse(this.responceText)\n    console.log(data);\n}\nmyReq.onerror = (err)=\u003e{\n    console.log(\"Error\",err)\n}\nmyReq.open('get','sample.com',true);\nmyReq.setRequestHeader('Accept','application/json');\nmyReq.send();\nconsole.log(myReq.response)\n```\n\n## Making requests using fetch\n\u003cli\u003eThe newer way of making requests via JS.\n\u003cli\u003eSupports promises. \n\u003cli\u003eNot supported in Internet Explorer.\n\n```js\nfetch('url',{header: { Accept: 'application/json'}})\n.then((res)=\u003e {\n    if(res.status!=200){\n        console.log(\"Problem\",res.status)\n        return;\n    }\n    res.json().then((data)=\u003e {\n        console.log(data)\n    })\n\n})\n.catch((err)=\u003e {console.log(err)})\n```\n### Chaining fetch requests\n\n```js\nconst url = \"https://swapi.dev/api/planets\";\nfetch(url).then((res)=\u003e{\n    return res.json()\n    \n})\n.then((data)=\u003e{\n    return data.results\n})\n.then((results)=\u003e{\n    const filmUrl = results[0].films[0];\n    return fetch(filmUrl)\n})\n.then((results)=\u003e{\n    return results.json()\n}).then((data)=\u003e{\n    console.log(data)\n})\n.catch((err)=\u003e{console.log(err)})\n```\n\n### Refactoring fetch requests\n```js\nconst checkStatusAndParse = (response)=\u003e{\n    if(!response.ok) throw new Error('Status code error')\n    return response.json();\n}\nconst printPlanets = (data)=\u003e{\n    console.log(\"FETCHED ALL PLANETS\")\n    data.results.forEach((planet)=\u003e{\n        console.log(planet.name)\n    })\n    return Promise.resolve(data.next)\n}\n\nconst fetchMorePlanets = (url)=\u003e{\n    return fetch(url);\n}\n\nfetch(url)\n.then(checkStatusAndParse)\n.then(printPlanets)\n.then(fetchMorePlanets)\n.then(checkStatusAndParse)\n.then(printPlanets)\n.catch((err)=\u003e{console.log(err)})\n```\n\n## Axios\n\u003cli\u003eA library for making http requests. \n\n```js\naxios.get(url).then((res)=\u003e{\n    console.log(res.data)\n})\n.catch((err)=\u003e{\n    console.log(err)\n})\n```\n\n## Sequential requests using axios\n```js\nconst showData = ({data})=\u003e{\n    data.results.forEach((planet) =\u003e {\n        console.log(planet.name)\n    })\n    return axios.get(data.next)\n}\n\naxios.get(url)\n.then(showData)\n.then(showData)\n```\n\n\u003chr\u003e\n\n\n\u003ch1 id=\"async-await\" align=center\u003eAsync and Await \u003c/h1\u003e\n\n## The async keyword\n\u003cli\u003eAsync functions always return a promise.\n\u003cli\u003eIf the function returns a value, the promise will be resolved with that value.\n\u003cli\u003eIf the function throws an exception, the promise will be rejected.\n\n```JS\nasync function hello(){\n    return \"Hey Guys\"\n}\nhello();\n// Promise(\u003cresolved\u003e: \"Hey Guys\")\nasync function huh(){\n    throw new Error(\"Oh no\")\n}\nhuh();\n// Promise(\u003crejected\u003e: Error: oh no)\nconst add  = async (a,b) =\u003e {\n    return a+b;\n}\n\nadd(24,35).then((value) =\u003e {console.log(value)})\n```\n\n## The Await keyword\n\u003cli\u003eWe can only use the await keyword inside of function declared with async.\n\u003cli\u003eAwait will pause the execution of the function, waiting for a promise to be resolved. \n\n```JS\nasync function getData(){\n    const res = await axios.get('https://swapi.dev/api/planets')\n    console.log(res.data)\n}\n```\n\n## Error handling in async Functions\n\u003cli\u003eWe can use catch while calling the async function as we know async functions always return promise.\n\n```JS\ngetData().catch((err) =\u003e {console.log(err)})\n```\n\n\u003cli\u003eWe can add a try and catch block\n\n```JS\nasync function getData(){\n    try{\n        const res = await axios.get('https://swapi.dev/api/planets')\n        console.log(res.data)\n    }\n    catch(err){\n        console.log(err)\n    }\n}\n```\n\n## Multiple Awaits\n\n```JS\nasync function animateRight(el, amt) {\n\tawait moveX(el, amt, 1000);\n\tawait moveX(el, amt, 1000);\n\tawait moveX(el, amt, 1000);\n\tawait moveX(el, amt, 1000);\n\tawait moveX(el, amt, 1000);\n\tawait moveX(el, amt, 1000);\n\tawait moveX(el, amt, 1000);\n\tawait moveX(el, amt, 1000);\n\tawait moveX(el, amt, 1000);\n\tawait moveX(el, amt, 1000);\n}\n```\n\n## Parallel vs Sequential requests\n\n```JS\n// SEQUENTIAL REQUEST\nasync function getData(){\n    // if I want to request 3 urls\n   const res = await axios.get(\"https://pokeapi.co/api/v2/pokemon/1\")\n   const res2 = await axios.get(\"https://pokeapi.co/api/v2/pokemon/2\")\n   const res3 = await axios.get(\"https://pokeapi.co/api/v2/pokemon/3\")\n   console.log(res.data)\n}\n```\n\nThese requests are happening in sequence, like second request will happen when first done.\n\n\n#### Awaiting in parallel\n\n```JS\nasync function getData(){\n    // if I want to request 3 urls\n   const res = axios.get(\"https://pokeapi.co/api/v2/pokemon/1\")\n   const res2 = axios.get(\"https://pokeapi.co/api/v2/pokemon/2\")\n   const res3 = axios.get(\"https://pokeapi.co/api/v2/pokemon/3\")\n   const poke1 = await res\n   const poke2 = await res2\n   const poke3 = await res3\n//    now res, res2, res3 are promises not data\n   console.log(poke1.data)\n}\n```\n\n## Refactoring with Promise.all\n\nPromise.all accepts an array of promises.\n\n```JS\nasync function getData(){\n   const res = axios.get(\"https://pokeapi.co/api/v2/pokemon/1\")\n   const res2 = axios.get(\"https://pokeapi.co/api/v2/pokemon/2\")\n   const res3 = axios.get(\"https://pokeapi.co/api/v2/pokemon/3\")\n   const results = await Promise.all([res,res2,res3])\n   console.log(results)\n}\n```\n\n\n\u003ch1 id=\"oops\"\u003ePrototypes, Classes, \u0026 the new operator\u003c/h1\u003e\n\n## What are protoypes?\nPrototypes are the mechanism by which JavaScript objects inherit features from one another.\n\n### A prototype-based language?\nJavaScript is often described as a prototype-based language — to provide inheritance, objects can have a prototype object, which acts as a template object that it inherits methods and properties from.\n\nAn object's prototype object may also have a prototype object, which it inherits methods and properties from, and so on. This is often referred to as a prototype chain, and explains why different objects have properties and methods defined on other objects available to them.\n\nWe can define prototypes of string like\n\n```JS\nString.prototype.getup  = function(){\n   return this.toUpperCase()\n}\n```\n\nWe can change already defined protoypes as well. For example\n\n```JS\nArray.prototype.pop = function(){\n    return \"Sorry\"\n}\n```\n\n## Object Oriented Programming in JavaScript\n\nThere are certain features or mechanisms which makes a Language Object-Oriented like: \n\n\u003cli\u003eObject\n\u003cli\u003eClasses\n\u003cli\u003eEncapsulation\n\u003cli\u003eInheritance\n\n### \u003cli\u003e Object\nAn Object is an instance of a class. Objects are everywhere in JavaScript almost every element is an Object whether it is a function, array, and string. \n\n\u003eA Method in javascript is a property of an object whose value is a function. \n\nObject can be created in two ways in JavaScript: \n\u003col\u003e\n\u003cli\u003eUsing an Object Literal \n\n```JS\n//Defining object\nlet person = {\n\tfirst_name:'Mukul',\n\tlast_name: 'Latiyan',\n\n\t//method\n\tgetFunction : function(){\n\t\treturn (`The name of the person is\n\t\t${person.first_name} ${person.last_name}`)\n\t},\n\t//object within object\n\tphone_number : {\n\t\tmobile:'12345',\n\t\tlandline:'6789'\n\t}\n}\nconsole.log(person.getFunction());\nconsole.log(person.phone_number.landline);\n```\n\n\u003cli\u003eUsing an Object Constructor\n\n```JS\n//using a constructor\nfunction person(first_name,last_name){\nthis.first_name = first_name;\nthis.last_name = last_name;\n}\n//creating new instances of person object\nlet person1 = new person('Mukul','Latiyan');\nlet person2 = new person('Rahul','Avasthi');\n\nconsole.log(person1.first_name);\nconsole.log(`${person2.first_name} ${person2.last_name}`);\n```\n\u003c/ol\u003e\n\u003cli\u003eUsing Object.create() method: \u003cbr\u003eThe Object.create() method creates a new object, using an existing object as the prototype of the newly created object. \n\n```JS\n// Object.create() example a\n// simple object with some properties\nconst coder = {\n\tisStudying : false,\n\tprintIntroduction : function(){\n\t\tconsole.log(`My name is ${this.name}. Am I\n\t\tstudying?: ${this.isStudying}.`)\n\t}\n}\n// Object.create() method\nconst me = Object.create(coder);\n\n// \"name\" is a property set on \"me\", but not on \"coder\"\nme.name = 'Mukul';\n\n// Inherited properties can be overwritten\nme.isStudying = true;\n\nme.printIntroduction();\n```\n\n### \u003cli\u003e Classes\nClasses are blueprint of an Object. A class can have many Object, because class is a template while Object are instances of the class or the concrete implementation. \n\n```JS\n// Defining class using es6\nclass Vehicle {\nconstructor(name, maker, engine) {\n\tthis.name = name;\n\tthis.maker = maker;\n\tthis.engine = engine;\n}\ngetDetails(){\n\treturn (`The name of the bike is ${this.name}.`)\n}\n}\n// Making object with the help of the constructor\nlet bike1 = new Vehicle('Hayabusa', 'Suzuki', '1340cc');\nlet bike2 = new Vehicle('Ninja', 'Kawasaki', '998cc');\n\nconsole.log(bike1.name); // Hayabusa\nconsole.log(bike2.maker); // Kawasaki\nconsole.log(bike1.getDetails());\n```\n\n\u003eunlike other Object Oriented Language there is no classes in JavaScript we have only Object. To be more precise, JavaScript is a prototype based object oriented language, which means it doesn’t have classes rather it define behaviors using constructor function and then reuse it using the prototype. \n\n\u003eJavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript’s existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance. \n\n### \u003cli\u003e Encapsulation\nThe process of wrapping property and function within a single unit is known as encapsulation. \n\n```JS\n//encapsulation example\nclass person{\n\tconstructor(name,id){\n\t\tthis.name = name;\n\t\tthis.id = id;\n\t}\n\tadd_Address(add){\n\t\tthis.add = add;\n\t}\n\tgetDetails(){\n\t\tconsole.log(`Name is ${this.name},Address is: ${this.add}`);\n\t}\n}\n\nlet person1 = new person('Mukul',21);\nperson1.add_Address('Delhi');\nperson1.getDetails();\n```\nSometimes encapsulation refers to hiding of data or data Abstraction which means representing essential features hiding the background detail.\n\n### \u003cli\u003e Inheritance\nIt is a concept in which some property and methods of an Object is being used by another Object. Unlike most of the OOP languages where classes inherit classes, JavaScript Object inherits Object i.e. certain features (property and methods)of one object can be reused by other Objects. \n\n```JS\n//Inheritance example\nclass person{\n\tconstructor(name){\n\t\tthis.name = name;\n\t}\n\t//method to return the string\n\ttoString(){\n\t\treturn (`Name of person: ${this.name}`);\n\t}\n}\nclass student extends person{\n\tconstructor(name,id){\n\t\t//super keyword to for calling above class constructor\n\t\tsuper(name);\n\t\tthis.id = id;\n\t}\n\ttoString(){\n\t\treturn (`${super.toString()},Student ID: ${this.id}`);\n\t}\n}\nlet student1 = new student('Mukul',22);\nconsole.log(student1.toString());\n```\n\n## Factory Functions\n```JS\nfunction makeColor(r, g, b) {\n    const color = {}\n    color.r = r;\n    color.g = g;\n    color.b = b;\n    color.rgb = function () {\n        const { r, g, b } = this;\n        return `rgb(${r}, ${b}, ${g})`\n    }\n    color.hex = function () {\n        const { r, g, b } = this;\n        return '#' + ((1 \u003c\u003c 24) + (r \u003c\u003c 16) + (g \u003c\u003c 8) + b).toString(16).slice(1)\n\n    }\n    return color;\n}\n```\n\nThis above function makes us an object. This is called factory function.\n\n## Constructor funcion\nFactory function pattern is not commonly used.\nInstead of this we use constructor pattern or constructor function.\n\n### The new operator\nThe new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function. \n\n\u003cpre\u003e\nnew constructor[([arguments])]\n\u003c/pre\u003e\n\n```JS\nfunction Car(make,model,year){\n    this.make = make\n    this.model = model\n    this.year = year\n}\n\nlet car1 = new Car(\"Audi\", \"Q7\", \"2022\")\n```\n\n\u003cli\u003econstructor\u003cbr\u003e\nA class or function that specifies the type of the object instance.\n\n\u003cli\u003earguments\u003cbr\u003e\nA list of values that the constructor will be called with.\n\u003col\u003e\n\u003cli\u003eCreates a blank, plain JavaScript object.\n\u003cli\u003eAdds a property to the new object (__proto__) that links to the constructor function's prototype object\n\u003cli\u003eBinds the newly created object instance as the this context (i.e. all references to this in the constructor function now refer to the object created in the first step).\n\u003cli\u003eReturns this if the function doesn't return an object.\u003c/ol\u003e\n\n\n## Classes in JavaScript\nWhenever we define a class, we define a constructor() inside of it. Constructor is a function which will run immediately when a object is created using this class.\n\n```JS\nclass Color{\n    constructor(r,g,b){\n        console.log(\"INSIDE CONSTRUCTOR\")\n        console.log(r,g,b)\n\n    }\n}\n\nconst c1 =  new Color(333,43,34)\n```\n\nWe can define object methods in class\n\n```JS\nclass Color{\n    constructor(r,g,b){\n        this.r = r\n        this.g = g\n        this.b = b\n    }\n    greet(){\n        const {r,g,b} = this\n        return `rgb(${r}, ${g}, ${b})`\n    }\n}\n\nconst c1 =  new Color(333,43,34)\n```\n\n## Extends, Super and Subclasses\nWe can inherit a class to another class using extends keyword \n\n```JS\nclass Pet {\n    constructor(name,age){\n        this.name = name\n        this.age = age\n    }\n    eat(){\n        return `${this.name} is eating`\n    }\n}\n\nclass Cat extends Pet{\n    meow(){\n        return \"MEOWWW\"\n    }\n}\n\nclass Dog extends Pet{\n    bark(){\n        return \"BARKWW\"\n    }\n}\n\nconst cat1 = new Cat(\"Losi\",5)\nconst dog1 = new Dog(\"Rockie\",7)\n```\n\n\u003cli\u003eThe super keyword is used to access and call functions on an object's parent.\n\n```JS\nclass Rectangle {\n  constructor(height, width) {\n    this.name = 'Rectangle';\n    this.height = height;\n    this.width = width;\n  }\n  sayName() {\n    console.log('Hi, I am a ', this.name + '.');\n  }\n  get area() {\n    return this.height * this.width;\n  }\n  set area(value) {\n    this._area = value;\n  }\n}\n\nclass Square extends Rectangle {\n  constructor(length) {\n    this.height; // ReferenceError, super needs to be called first!\n\n    // Here, it calls the parent class's constructor with lengths\n    // provided for the Rectangle's width and height\n    super(length, length);\n\n    // Note: In derived classes, super() must be called before you\n    // can use 'this'. Leaving this out will cause a reference error.\n    this.name = 'Square';\n  }\n}\n```\n\n\u003chr\u003e\n\n\n\u003ch1 id=\"node\"\u003eJavaScript with Node.js\u003c/h1\u003e\n\n\u003ctable\u003e\n\u003ctr\u003e\n\u003ctd\u003eJS in Browser\u003c/td\u003e\n\u003ctd\u003eJS with Node\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003eExecuted by adding script tags to an HTML document\u003c/td\u003e\n\u003ctd\u003eExecuted by running the NODE CLI from your terminal\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003eWe get access to the DOM and related objects(window)\u003c/td\u003e\n\u003ctd\u003eNO DOM exists\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003eCode can references variables in other files freely\u003c/td\u003e\n\u003ctd\u003eEach file is its own seperte world\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003eInclude libraries by adding script tags(more complicated solutions exist)\u003c/td\u003e\n\u003ctd\u003eInclude libraries by using NPM(Node Package Manager)\u003c/td\u003e\n\u003c/tr\u003e\n\u003c/table\u003e\n\n\n## Running JS code with Node\n\n```Bash\n$ node index.js # executes a file in te same directory caled index.js\n\n$ node # enters the NODE REPS\n```\n\n## Working with Modules in Node.js\nIf we want to share stuff between different node js files. We can make use of modules\n\n```JS\n// index.js\nconst message = require('./myscript.js')\nconsole.log(message)\n```\n\n```JS\n// myscript.js\nmodule.exports = 'Hi'\n```\n\n```Bash\n$ node index.js\n```\n\n## Invisible functions\nIf we are running index.js file, node will find index.js file and then it's going to wrap it inside a function like this\n\n```JS\nfunction (exports, require, module,__filename, __dirname){\n    const message = require('./myscript.js')\n    console.log(message)\n}\n```\n\nThis is a simple function that has some number of arguments. This function is going to be automatically invoked by node. Here are 5 arguments that are automatically provided.\n\n\u003ctable\u003e\n\u003ctr\u003e\n\u003ctd\u003eexports\u003c/td\u003e\n\u003ctd\u003eEquivalent to module.exports . We can technically export code using this, but it is easier to use 'module.exports' because of a little corner\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003erequire\u003c/td\u003e\n\u003ctd\u003eFunction to get access to the exports from another file\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003emodule\u003c/td\u003e\n\u003ctd\u003eObject that defines some properties + informtion about the current file\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003e__filename\u003c/td\u003e\n\u003ctd\u003eFull path + file name of this file\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003e__dirname\u003c/td\u003e\n\u003ctd\u003eFull path of this file\u003c/td\u003e\n\u003c/tr\u003e\n\u003c/table\u003e  \n\nWe can check these arguments by running -\n\n```JS\nconsole.log(arguments)\n```\n\n## The require cache\nModules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.\n\n\u003e Moules get only required once.\n\n## Debugging Node js\n\u003ctable\u003e\n\u003ctr\u003e\n\u003cth\u003enode inspect index.js\u003c/th\u003e\n\u003ctd\u003eStart up a debugger CLI and pause execution whenever a debugger statement is hit\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003cth\u003enode --inspect index.js\u003c/th\u003e\n\u003ctd\u003estart up a debugger instance and pause execution whenever a debugger statement is hit. Access the debugger at 'chrome://inspect'\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003cth\u003enode --inspect-brk index.js\u003c/th\u003e\n\u003ctd\u003eStart up a debugger instance and wait to execute until a debugger is connected. Access the debugger at 'chrome://inspect'\u003c/td\u003e\n\u003c/tr\u003e\n\u003c/table\u003e\n\n### CLI Debugger commands\n\n\u003ctable\u003e\n\u003ctr\u003e\n\u003cth\u003eC\u003c/th\u003e\n\u003ctd\u003eContinue execution until program ends or next debugger statement\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003cth\u003en\u003c/th\u003e\n\u003ctd\u003eRun the next line of code\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003cth\u003es\u003c/th\u003e\n\u003ctd\u003estep in to a function\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003cth\u003eo\u003c/th\u003e\n\u003ctd\u003eStep out of current function\u003c/td\u003e\n\u003c/tr\u003e\n\u003c/table\u003e\n\n#### Accessing Node js standard library modules\nWe can access node js provided inbuilt \u003ca href=\"https://nodejs.org/docs/latest-v12.x/api/\"\u003estandard library modules\u003c/a\u003e using require function.\n\nIf we want to use file system we can require fs just like this\n\n```JS\nconst fs = require('fs');\n```\n\n## callback pattern in Node js\nlet's use fs.readdir function which accepts callbacks.\n\nIf we want to use current directory, first argument we need to pass '.' in the function. The second argument is callback.\n\n```JS\nconst fs = require('fs');\nfs.readdir('.',(err,files)=\u003e{\n    if(err){\n        console.log(err)\n    }\n    console.log(files)\n})\n```\n\n## Process.cwd function\ncwd means current working directory.\n\n```JS\nconst fs = require('fs');\nfs.readdir(process.cwd(),(err,files)=\u003e{\n    if(err){\n        console.log(err)\n    }\n    console.log(files)\n})\n```\n\n## Running a Node program as an Executable\n\n```bash\n$ npm init -y\n```\nThis command will generate a file for us, package.json \n\n```JSON\n{\n  \"name\": \"project-1\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" \u0026\u0026 exit 1\"\n  },\n  \"keywords\": [],\n  \"author\": \"\",\n  \"license\": \"ISC\"\n}\n```\n\nHere we can see a key \"scripts\" so these are tiny script that do some automated tasks for us.\n\nWe can add another script that try to build our project\n\n```JSON\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" \u0026\u0026 exit 1\",\n    \"build\": \"npm run build\"\n  },\n```\n\nWe can add bin key in this file so that when we run this nls command in our terminal our index.js file will be executed.\n\n```JSON\n  \"bin\":{\n    \"nls\": \"index.js\"\n  }\n```\n\n\u003cli\u003eCreate package.json file with bin section\n\u003cli\u003eChange index.js file permissions\n\n```bash\n$ chmod +x index.js\n```\n\n\u003cli\u003eAdd comment to index.js file to allow it to be treated like an executable \n\n```JS\n#!/usr/bin/env node\n```\n\n\u003cli\u003eLink our project\n\n```bash\n$ npm link\n```\n\nNow our project(index.js) file is executable. We can execute it from anywhere in our system just by command nls.\n\n\u003e It's very useful for creating command line tools using node js.\n\n\n## Options to get to know which file is dir or file\n\u003cli\u003eMaintain an array of results from each lstat. As each callback is invoked, add the stats object to this array. When array is full, log everything in it.\n\u003cli\u003eWrap the lstat call with a promise, use async/await syntax to process lstat call one at a time\n\u003cli\u003eWrap the lstat call with a promise, use async/await + the Promise.all helper method to process lstat calls all at once.\n\nlet's implement most optimized solution(promise.all based)\n\n```JS\n#!/usr/bin/env node\nconst fs = require('fs');\nconst chalk = require('chalk')\nconst {lstat} = fs.promises;\n\nfs.readdir(process.cwd(),async (err,files)=\u003e{\n    if(err){\n        console.log(err)\n    }\nconst fileAr = files.map((file)=\u003e{return lstat(file)})\n    const stats = await Promise.all(fileAr)\n    \n    stats.forEach((stat,index)=\u003e{\n        if(stat.isFile()){\n            console.log(chalk.blue(files[index]))\n        }\n        else{\n            console.log(chalk.green(files[index]))\n        }\n    })\n})\n```\n\n## Taking inputs from commandline\n\nIf we console.log process.argv this will return an array and whatever we pass with our executable command that will be pushed into this array.\n\n```JS\nconsole.log(process.argv)\n```\n\n\u003chr\u003e\n\n### Thanks for reading this..\n\n\u003chr\u003e\n\n## Author: \u003ca href=\"https://www.github.com/tush-tr\"\u003eTushar Rajpoot\u003c/a\u003e\n## Publication: \u003ca href=\"https://kubekode.org\"\u003eKubekode\u003c/a\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003cimg width=\"44%\" src=\"https://github-readme-stats.vercel.app/api?username=tush-tr\u0026theme=react\u0026cache_seconds=30\u0026hide_border=truek\"/\u003e\u0026nbsp;\u0026nbsp;\u0026nbsp;\n  \u003cimg width=\"44%\" src=\"https://github-readme-streak-stats.herokuapp.com/?user=tush-tr\u0026theme=react\u0026cache_seconds=30\u0026hide_border=true\"/\u003e\n \u003cimg src=\"https://github-profile-summary-cards.vercel.app/api/cards/profile-details?username=tush-tr\u0026theme=dracula\"/\u003e\n\u003c/p\u003e","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftush-tr%2Fjavascript-is-love","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftush-tr%2Fjavascript-is-love","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftush-tr%2Fjavascript-is-love/lists"}