├── Gemfile ├── LICENSE ├── README.md ├── _config.yml ├── _layouts └── default.html ├── images ├── javascript-logo-banner.jpg └── strict.jpg ├── notes ├── closures.md ├── datatypes-in-javascript.md ├── event-loop.md ├── functions.md ├── hoisting.md ├── how-and-where-is-javascript.md ├── promises.md ├── strict.md ├── this.md ├── what-is-javascript.md └── what-is-the-truth.md └── scripts ├── async-await.js ├── asynchronous-pro.js ├── closures.js ├── event-loop.js ├── hoisting.js └── promise.js /Gemfile: -------------------------------------------------------------------------------- 1 | gem 'jekyll-theme-primer', '~> 0.5.4' -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | This is free and unencumbered software released into the public domain. 2 | 3 | Anyone is free to copy, modify, publish, use, compile, sell, or 4 | distribute this software, either in source code form or as a compiled 5 | binary, for any purpose, commercial or non-commercial, and by any 6 | means. 7 | 8 | In jurisdictions that recognize copyright laws, the author or authors 9 | of this software dedicate any and all copyright interest in the 10 | software to the public domain. We make this dedication for the benefit 11 | of the public at large and to the detriment of our heirs and 12 | successors. We intend this dedication to be an overt act of 13 | relinquishment in perpetuity of all present and future rights to this 14 | software under copyright law. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR 20 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 21 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | OTHER DEALINGS IN THE SOFTWARE. 23 | 24 | For more information, please refer to 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # **Javascript ☢ Notes _(cause I can't memorise them all)_ 🥴** 2 | 3 |
4 | JavaScript 5 |
6 | 7 | --- 8 | 9 |

10 | Made with Bootstrap 11 | License 12 | Stars 13 | Star Badge 14 |

15 | 16 | 🕉 _(Taking God's name, because.)_ 17 | 18 | ```md 19 | “Curiosity is the lust of the mind.”- Thomas Hobbes 20 | ``` 21 | 22 | Hopefully going to cover everything... 23 | 24 | --- 25 | 26 | ## ✨ **Contents** 27 | 28 | ⚫ What on 🌍 is JavaSrcipt? 😶 [ Read ▶ ](./notes/what-is-javascript.md) 29 | 30 | ⚫ How and Where JavaScript works? 😫 31 | 32 | ⚫ Datatypes in JavaScript. 😙 [ Read ▶ ](./notes/datatypes-in-javascript.md) 33 | 34 | ⚫ What is the Truth? 🤥 [ Read ▶ ](./notes/what-is-the-truth.md) 35 | 36 | ⚫ Event Loop. 🔁 😵 [ Read ▶ ](./notes/event-loop.md) 37 | 38 | ⚫ Hoisting 🏴‍☠️ ? ...is this a Ship? 🤨 [ Read ▶ ](./notes/hoisting.md) 39 | 40 | ⚫ Closures... That one question I forgot... 😥 [ Read ▶ ](./notes/closures.md) 41 | 42 | ⚫ Are you looking for `this`? '🙄 [ Read ▶ ](./notes/this.md) 43 | 44 | ⚫ Functions... Calls, Arguments and Return values. 😅 [ Read ▶ ](./notes/functions.md) 45 | 46 | ⚫ Arrow Functions... Cooler brother of Functions. 🤐 47 | 48 | ⚫ Pure and Impure Functions??? 😯 49 | 50 | ⚫ Higher Order Functions 🤔 & Callbacks _(JS will she won't)_ 😓 51 | 52 | ⚫ Objects... They run the show. 🤗 53 | 54 | ⚫ Beyond console.log() 🖥️ 55 | 56 | ⚫ Promises 🤝 and Async/Await 🤯 [ Read ▶ ](./notes/promises.md) 57 | 58 | ⚫ Modules 😄 59 | 60 | --- 61 | 62 | ## 🚀 **References** 63 | 64 | ➡ [Mozilla](https://developer.mozilla.org/en-US/docs/Web/JavaScript) 65 | ➡ [Fireship.io](https://fireship.io/courses/javascript/) 66 | 67 | > Collected with 🖤 by Jainam Desai 68 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-primer 2 | 3 | google_analytics: UA-166801765-1 4 | -------------------------------------------------------------------------------- /_layouts/default.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | {% seo %} 9 | 10 | 11 | 12 |
13 | 14 | {{ content }} 15 | 16 | {% if site.github.private != true and site.github.license %} 17 | 20 | {% endif %} 21 |
22 | 23 | 24 | {% if site.google_analytics %} 25 | 33 | {% endif %} 34 | 35 | -------------------------------------------------------------------------------- /images/javascript-logo-banner.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/th3c0d3br34ker/javascript-notes/eef025208396b5b342ef2157665e843694eba983/images/javascript-logo-banner.jpg -------------------------------------------------------------------------------- /images/strict.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/th3c0d3br34ker/javascript-notes/eef025208396b5b342ef2157665e843694eba983/images/strict.jpg -------------------------------------------------------------------------------- /notes/closures.md: -------------------------------------------------------------------------------- 1 | # **Closures** 2 | 3 | [Home](../README.md) / Closures 4 | 5 | --- 6 | 7 | A `closure` is the combination of a function bundled together (enclosed) with references to its surrounding state (the `lexical environment`). 8 | 9 | In other words, a closure is a function that has `access` to its `outer function scope even after the return of the outer function`. This allows the inner function to access the `variables` and arguments even after the outer function has finished. 10 | 11 | Here is an implementation of a Closure: 12 | 13 | ```js 14 | function outer(n) { 15 | let x = n; // persits in memory after outer is popped off the call stack 16 | 17 | function inner() { 18 | return x; 19 | } 20 | 21 | return inner; 22 | } 23 | 24 | // Creates the Closure. 25 | const closure = outer(1); 26 | 27 | // Operates within its context or lexical environment 28 | console.log(closure()); // 1 29 | ``` 30 | 31 | This happens because the inner function preserves the scope chain of the enclosing function at the time the enclosing function was executed, and thus can access the enclosing function's variables. 32 | 33 | ## **Scope chains in JavaScript ⛓️** 34 | 35 | JavaScript has three scope chains: 36 | 37 | ✅ Its own block - local variables and its own arguments. 38 | 39 | ✅ Its outer functions's block - variables a and arguments of its parent function. 40 | 41 | ✅ Global block - anything defined in the global block. 42 | 43 | Here is an another example: 44 | 45 | ```js 46 | function counter(x) { 47 | function increment(y) { 48 | return x + y; 49 | } 50 | return increment; 51 | } 52 | 53 | const incrementBy1 = counter(1); 54 | incrementBy1(1); // 2 55 | incrementBy1(10); // 11 56 | ``` 57 | 58 | See the above code [here](../scripts/closures.js). 59 | 60 | --- 61 | 62 | See Also: 63 | 64 | > ⚫ Event Loop. 🔁 😵 [ Read ▶ ](./event-loop.md) 65 | > ⚫ What is the Truth? 🤥 [ Read ▶ ](./what-is-the-truth.md) 66 | > ⚫ Hoisting 🏴‍☠️ ? ...is this a Ship? 🤨 [ Read ▶ ](./hoisting.md) 67 | -------------------------------------------------------------------------------- /notes/datatypes-in-javascript.md: -------------------------------------------------------------------------------- 1 | # **Datatypes in JavaScript. 😙** 2 | 3 | [Home](../README.md) / Datatypes in JavaScript. 😙 4 | 5 | --- 6 | 7 | There are primarily two types of datatypes in JavaScript: 8 | 9 | ➡ [Primitives 💫](#primitives-) 10 | 11 | ➡ [Objects ☯](#objects-) 12 | 13 | --- 14 | 15 | ## **Primitives 💫** 16 | 17 | The lowest level building blocks in JavaScript are primitives, which include: undefined, null, string, number, bigint, boolean, and symbol. All primitives are immutable. 18 | 19 | ```js 20 | > typeof 5; // number 21 | > typeof "Mon" // string 22 | > typeof null // null 23 | > typeof true // boolean 24 | ``` 25 | 26 | JavaScript provides seven different primitive data types: 27 | 28 | | Data Types | Examples | 29 | | ----------- | --------------------------------------------------------------------- | 30 | | `undefined` | A variable that has not been assigned a value is of type `undefined`. | 31 | | `null` | No value. | 32 | | `string` | `'a', 'aa', 'aaa', 'Hello!'` | 33 | | `number` | `-5, 2, 0.1` | 34 | | `boolean` | `true, false` | 35 | | `object` | A collection of properties, with key and value pair. | 36 | | `symbol` | Represents a unique identifier. | 37 | 38 | --- 39 | 40 | ## **Objects ☯** 41 | 42 | Anything that is not a primitive is an Object, or a descendant of it. Objects are collections of key/value pairs and used as the building block for more complex data structures. 43 | 44 | ```js 45 | typeof {}; // object 46 | typeof []; // object 47 | typeof function () {}; // function (which inherits from object) 48 | ``` 49 | 50 | --- 51 | 52 | ## **The difference between `undefined` and `null`** 53 | 54 | ✅ `undefined`: It is the default value for any variable which is declared but has no value assigned to it, OR a function which doesn't return anything. 55 | 56 | ```js 57 | let x; 58 | 59 | console.log(x); // undefined 60 | 61 | // OR 62 | 63 | function meh() {} 64 | 65 | console.log(meh()); // undefined 66 | ``` 67 | 68 | ✅ `null`: It represents "empty" value, which a programmer would assign explicitly. 69 | 70 | ```js 71 | let x = null; 72 | 73 | console.log(x); // null 74 | 75 | // OR 76 | 77 | function meh() { 78 | return null; 79 | } 80 | 81 | console.log(meh()); // null 82 | ``` 83 | 84 | --- 85 | 86 | ## **JavaScripts TWO equality operators** 87 | 88 | JavaScript porvides two equality operators `==` and `===`. Since this is the case there is a lot of confusion 89 | 90 | ➡ `==`: It is called the equality operator. It only compares the data. 91 | 92 | ➡ `===`: It is called the identity operator. It compares both data and the data-type. 93 | 94 | Let's understand the the differece between them with an example. 95 | 96 | ```js 97 | // Exmaple 1 98 | console.log("5" == 5); // true 🤯 99 | 100 | //Example 2 101 | console.log("5" === 5); // false 😋 102 | ``` 103 | 104 | This happens because JavaScript will run a converstion before running the comparision. To handle this you should always use the `===` operator instead of the `==` operator. 105 | 106 | ```md 107 | Lets recapitulate 📝: 108 | 109 | ➡ There are primarily two types of datatypes in JavaScript: Primitives and Objects. 110 | 111 | ➡ Primitive data-types can not be mutated, where as Objects can be mutated. 112 | 113 | ➡ Always use the `===` operator instead of the `==` operator for comparison. 114 | ``` 115 | 116 | --- 117 | 118 | See Also: 119 | 120 | > ⚫ What is the Truth? 🤥 [ Read ▶ ](./what-is-the-truth.md) 121 | > ⚫ Promises 🤝 and Async/Await 🤯 [ Read ▶ ](./promises.md) 122 | -------------------------------------------------------------------------------- /notes/event-loop.md: -------------------------------------------------------------------------------- 1 | # **Event Loop. 🔁 😵** 2 | 3 | [Home](../README.md) / Event Loop? 🔁 😵 4 | 5 | --- 6 | 7 | ## Some Concepts or go directly to [Event Loops](#event-loops-) 8 | 9 | JavaScript has a concurrency model based on an event loop, which is responsible for executing the code, collecting and processing events, and executing queued sub-tasks. This model is quite different from models in other languages like C and Java. 10 | 11 | ```md 12 | Single-Threaded means that JS can only run one instruction at a time, even if your CPU has multiple cores and available threads. 13 | ``` 14 | 15 | Some Runtime Concepts: 16 | 17 | ➡ [Stack 🍔](#stack-) 18 | ➡ [Heap ☁️](#heap-) 19 | ➡ [Queue 🍞](#queue-) 20 | 21 | ### **Stack 🍔** 22 | 23 | ### **Heap ☁️** 24 | 25 | ### **Queue 🍞** 26 | 27 | --- 28 | 29 | ## **Event Loops 😵** 30 | 31 | Event Loop is essentially an infinite loop which keeps on checking if something exists in the queue. Its most basic implementation can be imagined as: 32 | 33 | ```js 34 | while (queue.waitForMessage()) { 35 | queue.processNextMessage(); 36 | } 37 | ``` 38 | 39 | Here is an example to understand better: 40 | 41 | ```js 42 | const first = () => console.log("First"); 43 | const second = () => setTimeout(() => console.log("Second"), 1000); 44 | const third = () => console.log("Third"); 45 | 46 | first(); 47 | second(); 48 | third(); 49 | 50 | // Output 51 | // JavaScript will first run the synchronous code then it will look for messages in the queue. 52 | 53 | First; 54 | Third; 55 | Second; 56 | ``` 57 | 58 | See the above code [here](../scripts/event-loops.js) 59 | 60 | ### **Zero delays** 61 | 62 | Now, if we set the setTimeout with a delay of `0` (zero) milliseconds doesn't execute the callback function after the given interval. 63 | 64 | ```js 65 | const second = () => setTimeout(() => console.log("Second"), 0); 66 | ``` 67 | 68 | The output will remain the same! 🤯 69 | 70 | ### **Non-blocking** 71 | 72 | A property of the event loop model is that JavaScript, unlike a lot of other languages, never blocks. Handling I/O is typically performed via events and callbacks, so when the application is waiting for a database query to return or an XHR/API request to return, it can still process other things like user input. 73 | 74 | ```md 75 | Lets recapitulate 📝: 76 | 77 | For each round of Event Loop JavaScript will: 78 | 79 | ➡ Run synchronous code. 80 | ➡ Run [Promise](/promises.md) or microtask callbacks. 81 | ➡ Run asynchronous code. 82 | ``` 83 | 84 | --- 85 | 86 | See Also: 87 | 88 | > ⚫ Promises 🤝 and Async/Await 🤯 [ Read ▶ ](./promises.md) 89 | > ⚫ Datatypes in JavaScript. 😙 [ Read ▶ ](./datatypes-in-javascript.md) 90 | -------------------------------------------------------------------------------- /notes/functions.md: -------------------------------------------------------------------------------- 1 | # **Functions... Calls, Arguments and Return values. 😅** 2 | 3 | [Home](../README.md) / Functions... Calls, Arguments and Return values. 😅 4 | 5 | --- 6 | 7 | ## **Contents** ✨ 8 | 9 | ➡ [Functions](functions) 10 | 11 | ➡ 12 | 13 | --- 14 | 15 | # **Function** 16 | 17 | Every function in JavaScript is a `Function` object. 18 | 19 | --- 20 | 21 | See also 22 | 23 | > ⚫ Event Loop. 🔁 😵 [ Read ▶ ](./event-loop.md) 24 | > ⚫ Closures [ Read ▶ ](./closures.md) 25 | -------------------------------------------------------------------------------- /notes/hoisting.md: -------------------------------------------------------------------------------- 1 | # **Hoisting 🏴‍☠️ ? ...is this a Ship? 🤨** 2 | 3 | [Home](../README.md) / Hoisting 🏴‍☠️ ? ...is this a Ship? 🤨 4 | 5 | --- 6 | 7 | `Hoisting` means that your declarations, i.e. functions and variables, will always be placed in memory at the top of the execution context. 8 | 9 | Hoisting was thought up as a general way of thinking about how `execution context` (specifically the creation and execution phases) work in JavaScript. However, the concept can be a little confusing at first. When the JavaScript engine gets our script, the first thing it does is setting up memory for the data in our code. No code is executed at this point, it’s just preparing everything for execution. 10 | 11 | See an Example in action: 12 | 13 | ```js 14 | // hoisting 🏴‍☠️ is as if your `function fun() {}` was located here. 15 | 16 | fun(); // works. 17 | 18 | function fun() {} 19 | ``` 20 | 21 | > Notice how the function below can be called before it’s actually declared. That’s hoisting in action. 22 | 23 | **❗❗ Important point to remember ❗❗** 24 | 25 | `Only declarations are hoisted` 26 | 27 | JavaScript only hoists declarations, not initializations. If a variable is declared and initialized after using it, the value will be undefined. For Example: 28 | 29 | ## **Hoisting with var, let and const 😗** 30 | 31 | ```js 32 | console.log(n); // Returns undefined, as only declaration was hoisted, no initialization has happened at this stage. 33 | 34 | var n; // Declaration 35 | n = 5; // Initialization 36 | 37 | console.log(n); //Throws an error, although was hoisted, no initialization has happened at this stage. Same is the case with var. 38 | 39 | let n; // Declaration 40 | n = 5; // Initialization 41 | ``` 42 | 43 | ## **Using 'strict' 😛** 44 | 45 | JavaScript in 'strict' mode does not allow hoisting. 46 | 47 | ```js 48 | use 'strict'; 49 | 50 | fun(); // no longer works. 51 | 52 | function fun() {} 53 | ``` 54 | 55 | Read more about 'strict' mode [here](./strict.md). 56 | 57 | ```md 58 | Lets recapitulate 📝: 59 | 60 | ➡ Functions and variables are stored in memory for an execution context before we execute our code. This is called hoisting. 61 | 62 | ➡ Functions are stored with a reference to the entire functions, variables with the var keyword with the value of undefined, and variables with the let and const keyword are stored uninitialized. 63 | 64 | ➡ Using 'strict' mode prevents this unruly 🤒 behaviour of JavaScript. 65 | ``` 66 | 67 | See the above code [here](../scripts/hoisting.js). 68 | 69 | Read more [here](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting). 70 | 71 | --- 72 | 73 | See Also: 74 | 75 | > ⚫ What is the Truth? 🤥 [ Read ▶ ](./what-is-the-truth.md) 76 | > ⚫ Event Loop. 🔁 😵 [ Read ▶ ](./event-loop.md) 77 | > ⚫ Promises 🤝 and Async/Await 🤯 [ Read ▶ ](./promises.md) 78 | -------------------------------------------------------------------------------- /notes/how-and-where-is-javascript.md: -------------------------------------------------------------------------------- 1 | # How and Where JavaScript works? 😫 2 | 3 | [Home](../README.md) / How and Where JavaScript works? 😫 4 | 5 | In JavaScript everything is runs in the `Execution Context`. The whole file is a Execution context itself. 6 | -------------------------------------------------------------------------------- /notes/promises.md: -------------------------------------------------------------------------------- 1 | # **Promises 🤝 and Async/Await 🤯** 2 | 3 | [Home](../README.md) / Promises 🤝 and Async/Await 🤯 4 | 5 | --- 6 | 7 | JavaScript is a single-threaded programming language yet everything on the web is either blocking 🛑 or time consuming🕓! This means asynchronous processing is an essential skill for any JavaScript developer. Before we understand Async/Await we need to understand Promise. 8 | 9 | ## **Contents** ✨ 10 | 11 | ➡ [Promise 🤝](#promise-) 12 | 13 | ➡ [Async/Await](#asyncawait-) 14 | 15 | --- 16 | 17 | ## **Promise 🤝** 18 | 19 | A Promise represents a value which is unknown now, but may become known at a later time. 20 | 21 | A Promise can be in one of `three` states: 22 | 23 | ➡ **Pending**, when the final value is not available yet. This is the only state that may transition to one of the other two states. 24 | 25 | ➡ **Fulfilled**, when and if the final value becomes available. A fulfillment value becomes permanently associated with the promise. This may be any value, including `undefined`. 26 | 27 | ➡ **Rejected**, if an error prevented the final value from being determined. A rejection reason becomes permanently associated with the promise. This may be any value, including `undefined`, though it is generally an Error object, like in exception handling. 28 | 29 | Promises work in two phases. 30 | 31 | ➡ Creation of a Promise 32 | ➡ Consumption of a Promise 33 | 34 | Promise are create with the `new Promise()` constructor initially in the pending state, and provides references to the resolving functions that can be used to change its state. 35 | 36 | Here is how you would create one: 37 | 38 | ```js 39 | const getFruit = (name) => { 40 | const fruits = { 41 | mango: "🥭", 42 | apple: "🍎", 43 | banana: "🍌", 44 | avocado: "🥑", 45 | }; 46 | 47 | let flag = fruits[name]; 48 | 49 | return new Promise((resolve, reject) => { 50 | if (flag) { 51 | resolve("Yay there is Fruit! 😄"); 52 | } else { 53 | reject("Sorry there's no Fruit 😔"); 54 | } 55 | }); 56 | }; 57 | ``` 58 | 59 | The next step is to consume the above Promise. Promises are either `resolved` or `rejected`. If a promise is `resolved` it means that it ran successfully and has returned a value we can use. If a promise is `rejected` it means that it has failed to run properly. 60 | 61 | Here is how you would consume a Promise: 62 | 63 | ```js 64 | getVeggie("mango") 65 | .then((response) => console.log(response)) 66 | .catch((error) => console.log(error)); 67 | ``` 68 | 69 | If the promise is `resolved` then the `then()` is executed. If it fails then `catch()` is executed. 70 | 71 | > It is very important to have a catch() for proper error handling. 72 | 73 | See the above code [here](../scripts/promise.js). 74 | 75 | Read more [here](https://github.com/tc39/proposal-promise-any). 76 | 77 | --- 78 | 79 | ## **Async/Await 🤯** 80 | 81 | Now that we understand Promises. Async/Await is nothing but “Syntactic Sugar” to make asynchronous code look like synchronous code. 82 | 83 | Creating a Promise based function: 84 | 85 | ```js 86 | const getVeggie = (name) => { 87 | const veggies = { 88 | mango: "🥭", 89 | apple: "🍎", 90 | banana: "🍌", 91 | avocado: "🥑", 92 | }; 93 | 94 | console.log("returned", name); 95 | return veggies[name]; 96 | }; 97 | 98 | const getSalad = async () => { 99 | const mango = await getVeggie("mango"); 100 | const apple = await getVeggie("apple"); 101 | const avocado = await getVeggie("avocado"); 102 | const banana = await getVeggie("banana"); 103 | 104 | return [mango, apple, avocado, banana]; 105 | }; 106 | 107 | // The above code is same as returning a new Promise() 108 | ``` 109 | 110 | > Note: 111 | > getVeggie() is just a helper function. It represents time consuming function calls like API calls and Database lookups. 112 | 113 | The way of consuming the Promise remains the same. Here is how you would consume a Promise: 114 | 115 | ```js 116 | getSalad() 117 | .then((response) => console.log(response)) 118 | .catch((error) => console.log(error)); 119 | ``` 120 | 121 | That's pretty much the introduction to Async/Await. 122 | 123 | See the above code [here](../scripts/async-await.js). 124 | 125 | --- 126 | 127 | ## **Hold Up! There is MORE 😶** 128 | 129 | Let's go a bit Deeper 😏. Understanding how to use Promise isn't enough. Now we try to use it in a better way. 130 | 131 | Here is a faster version of the `getSalad()` function: 132 | 133 | ```js 134 | const getSaladFaster = async () => { 135 | const mango = getVeggie("mango"); 136 | const apple = getVeggie("apple"); 137 | const avocado = getVeggie("avocado"); 138 | const banana = getVeggie("banana"); 139 | 140 | return Promise.all([mango, apple, avocado, banana]); 141 | }; 142 | ``` 143 | 144 | > Note: 145 | > This is only useful when these requests are not depended on each other. 146 | 147 | The fundamental difference is that all the function calls to the `getVeggie()` function is done at once! Yep, you read it right 😋. If this was an API call over the internet, it means that you could make requests to all the resources at once, saving a lot of time. 148 | 149 | Here is an example if each Veggie took 1s to load: 150 | 151 | ```js 152 | const getVeggie = async (name) => { 153 | // Stop the Execution thread for 1s. 154 | await delay(1000); 155 | 156 | const veggies = { 157 | mango: "🥭", 158 | apple: "🍎", 159 | banana: "🍌", 160 | avocado: "🥑", 161 | }; 162 | 163 | console.log("returned", name); 164 | return veggies[name]; 165 | }; 166 | ``` 167 | 168 | The `delay(time)` funtion blocks the thread for 1000ms or 1s. 169 | Running the `getSalad()` and `getSaladFaster()` will result in huge time difference. 170 | 171 | ```js 172 | getSalad().then(log); // ~4sec 173 | getSaladFaster().then(log); // ~1sec 174 | ``` 175 | 176 | See the above code [here](../scripts/asynchronous-pro.js) and try it yourself. 177 | 178 | ```md 179 | Lets recapitulate 📝: 180 | 181 | ➡ A Promise represents a value which is unknown now, but may become known at a later time. 182 | 183 | ➡ It can exist in one of the three states: Pending, Fullfiled or Rejected. 184 | 185 | ➡ Async/Await is just the “Syntactic Sugar” to make asynchronous code look like synchronous code. 186 | 187 | ➡ Promise is a Micro-task. Therefore, it has priority over Macro-tasks. 188 | ``` 189 | 190 | --- 191 | 192 | See Also: 193 | 194 | > ⚫ Event Loop. 🔁 😵 [ Read ▶ ](./event-loop.md) 195 | > ⚫ What is the Truth? 🤥 [ Read ▶ ](./what-is-the-truth.md) 196 | > ⚫ Hoisting 🏴‍☠️ ? ...is this a Ship? 🤨 [ Read ▶ ](./hoisting.md) 197 | -------------------------------------------------------------------------------- /notes/strict.md: -------------------------------------------------------------------------------- 1 | # **JavaScript being 'strict' 😬** 2 | 3 | [Home](../README.md) / JavaScript being 'strict' 😬 4 | 5 | JavaScript has a lot on inconsistencies which can be managed by using the `'strict mode'`. TypeScript uses this by default. It was introduced in ECMAScript 5, is a way to opt in to a restricted variant of JavaScript, thereby implicitly opting-out of the default `"sloppy mode"`. 6 | 7 | > The default, non-strict mode referred to as "sloppy mode". This isn't an official term, but used conventionally. 8 | 9 | ```md 10 | Strict mode makes several changes to normal JavaScript semantics: 11 | 12 | ➡ Eliminates some JavaScript silent errors by changing them to throw errors. 13 | 14 | ➡ Fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that's not strict mode. 15 | 16 | ➡ Prohibits some syntax likely to be defined in future versions of ECMAScript. 17 | ``` 18 | 19 | Here is how you would invoke the strict mode: 20 | 21 | ```js 22 | "use strict"; // That's it! 😛 23 | 24 | message = "Its gonna be 'strict' now! 😬"; // throws an error, Since 'message' not declared 25 | ``` 26 | 27 | ## **Should you use 'strict' mode** 🤔 28 | 29 | To maintain your sanity you should. 30 | 31 | [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) explains: 32 | 33 | ```md 34 | Strict mode makes several changes to normal JavaScript semantics. First, strict mode eliminates some JavaScript silent errors by changing them to throw errors. 35 | ``` 36 | 37 | This is highly desirable. I know that sounds counterintuitive. Why would you want more errors in your code? 38 | 39 | Here’s the thing: there were already errors in your code. The browser just wasn’t telling you about them, so they might crop up in unexpected ways that are harder to find. 40 | 41 | Turning on strict mode helps you find errors sooner, before they become bigger problems. And it forces you to write better code. 42 | 43 | > ![Strict Meme](../images/strict.jpg) 44 | 45 | Read more [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) and [here](https://www.w3schools.com/js/js_strict.asp). 46 | 47 | --- 48 | 49 | See Also: 50 | 51 | > ⚫ Event Loop. 🔁 😵 [ Read ▶ ](./event-loop.md) 52 | > ⚫ What is the Truth? 🤥 [ Read ▶ ](./what-is-the-truth.md) 53 | > ⚫ Hoisting 🏴‍☠️ ? ...is this a Ship? 🤨 [ Read ▶ ](./hoisting.md) 54 | -------------------------------------------------------------------------------- /notes/this.md: -------------------------------------------------------------------------------- 1 | # **Are you looking for `this`? 🙄** 2 | 3 | [Home](../README.md) / Are you looking for `this`? 🙄 4 | 5 | --- 6 | 7 | ## **What is `this` 😥** 8 | 9 | In JavaScript `this` refers to the current object that is executing the current function. It has different values depending on where it is used. 10 | 11 | Read more or about objects [here](./objects.md). 12 | 13 | ## The `this` reference 😳 14 | 15 | ✅ If the function is inside an Object then `this` refers to the that object. 16 | 17 | Example: 18 | 19 | ```js 20 | const cookie = { 21 | flavour: "chocolate", 22 | eat() { 23 | console.log(`I am a ${this.flavour} 🍪 and I was eaten!`); 24 | }, 25 | }; 26 | 27 | Cookie.eat(); 28 | 29 | // This is another way of writing the above code. 30 | const cookie = { 31 | flavour: "chocolate", 32 | eat: function () { 33 | console.log(`I am a ${this.flavour} 🍪 and I was eaten!`); 34 | }, 35 | }; 36 | 37 | // Both the codes are same. 38 | ``` 39 | 40 | This will not work if we use it inside an [Arrow Function](./arrow-functions.md) or inside a nested function. 41 | 42 | Example 43 | 44 | ```js 45 | // this will not work 46 | const cookie = { 47 | flavour: "chocolate", 48 | eat: () => { 49 | console.log(`I am a ${this.flavour} 🍪 and I was eaten!`); 50 | }, 51 | }; 52 | 53 | // OR 54 | 55 | const cookie = { 56 | flavours: ["chocolate", "stawberry", "vanilla"], 57 | eatAllCookies() { 58 | this.flavours.forEach(function (flavour) { 59 | // 👈 Anonymous nest function 60 | console.log(`I am ${flavour} 🍪 and I was eaten!`); // 👈 Will output "I am 'undefined' and I was eaten!" 61 | }); 62 | }, 63 | }; 64 | ``` 65 | 66 | To bind the object we need to pass the `this` object as an argument to the `forEach()` function. 67 | 68 | ```js 69 | const cookie = { 70 | flavours: ["chocolate", "stawberry", "vanilla"], 71 | eatAllCookies() { 72 | this.flavours.forEach(function (flavour) { 73 | console.log(`I am ${flavour} 🍪 and I was eaten!`); 74 | }, this); // 👈 here this refers to the current "flavours" array, which in turn is an object. 75 | }, 76 | }; 77 | 78 | // Works like a charm 😋 79 | cookie.eatAllCookies(); 80 | ``` 81 | 82 | --- 83 | 84 | ✅ If the function is a regular function then `this` refers to the `window` object in browser and the `global` object in node. 85 | 86 | Example: 87 | 88 | ```js 89 | function eatCookie() { 90 | console.log(this); 91 | console.log("this doesn't have a 🍪 object"); 92 | } 93 | 94 | // It will print the window object if run in browser and global if run in node. 95 | ``` 96 | 97 | **We can prevent `this` from binding to the global if we use `strict` mode.** 98 | 99 | > `this` is `undefined` in a normal function when using the `strict` mode. 100 | 101 | ```js 102 | "use strict"; 103 | 104 | function eatCookie() { 105 | console.log(this); 106 | console.log("this doesn't have anything!"); 107 | } 108 | 109 | // the above code will not log the global or window object, instead it will print 'undefined'. 110 | ``` 111 | 112 | `this` again behaves different if we invoke a function using the `new` operator. 113 | 114 | ```js 115 | function Cookie() { 116 | this.flavour = "I am a chocolate 🍪"; 117 | console.log(this.flavour, "and I was eaten!"); 118 | } 119 | 120 | const cookie = new Cookie(); 121 | ``` 122 | 123 | When we use the `new` operator, it creates a new empty object `{ }`. Then names that object `Cookie` and adds `flavour` property to it. 124 | 125 | --- 126 | 127 | See also 128 | 129 | > ⚫ Event Loop. 🔁 😵 [ Read ▶ ](./event-loop.md) 130 | > ⚫ Closures [ Read ▶ ](./closures.md) 131 | -------------------------------------------------------------------------------- /notes/what-is-javascript.md: -------------------------------------------------------------------------------- 1 | # **What on 🌐 is JavaSrcipt? 😵** 2 | 3 | [Home](../README.md) / What on 🌐 is JavaSrcipt? 4 | 5 | --- 6 | 7 | ```text 8 | JavaScript is a synchronous, single-threaded language. 9 | ``` 10 | 11 | ➡ [History 🌍](#history-) 12 | 13 | ➡ [Current Status 💫](#current-status-) 14 | 15 | ➡ [Defination 🚀](#defination-) 16 | 17 | --- 18 | 19 | ## **History 🌍** 20 | 21 | To understand JavaScript we have to go waaaay back to its creation! 22 | JavaScript is a scripting language written by Brendan Eich in 1995 for the Netscape Navigator browser under the working name of **“Mocha”**. After being renamed to **“JavaScript”**, it was standardized by [ECMA International](http://www.ecma-international.org/) as ECMA-262 or [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) in 1997. The authoritative group of people/organizations in charge of the standard is known as TC-39. 23 | 24 | ```text 25 | And then God said, “Let there be JavaScript” 26 | ``` 27 | 28 | Over the next 25 years, it would see a variety of highs and lows. The most notable releases include 29 | 30 | ➡ ES1 1997. 31 | ➡ ES2 1998. 32 | ➡ ES3 1999. The longest-standing version of early JS. 33 | ➡ ES4 Never finalized. 34 | ➡ ES5 2009. Added JSON, strict mode, functional array methods, and more. 35 | ➡ ES6 2015. Added classes, promises, arrow functions, let/const, and much more. 36 | ➡ ES7, ES8, ES9, ESNext. Modern updates are now being released annually. 37 | 38 | You can learn more about ECMAScript [here](https://github.com/tc39/ecma262#ecmascript). 39 | 40 | > This establishes the fact that it has nothing to do with Java. 🤗 41 | 42 | ## **Current Status 💫** 43 | 44 | JavaScript is continuously being developed with new additions added to it with every iteration. This is what makes it the most hated/loved language in the world! 45 | 46 | ## **Defination 🚀** 47 | 48 | Let's breakdown the various key terms associated to JavaScript: 49 | 50 | ✅ **High-level** 51 | 52 | JavaScript is a `high-level` programming language. It essentially means that when you run a JavaScript code you don't think about allocating memory or getting a thread from the CPU to run your code. In other words, the level of `abstraction` is provided by a programming language. You get features like `garbage-collectors`, `dynamic-typing` which simplify a programmer's job. 53 | 54 | ✅ **Interpreted** 55 | 56 | JavaScript is a JIT or Just-In-Time compiled language. 57 | 58 | ✅ **Weakly Typed** 59 | 60 | Unlike most programming languages, JavaScript is weakly typed. It simply means the datatypes become known at runtime. 61 | 62 | Here is a small example 63 | 64 | ```js 65 | // JavaScript 66 | let message = "Keep smiling! 😄"; // 👈 Notice we don't mention a datatype. 67 | const happiness = 100; // 👈 Notice we don't mention a datatype. 68 | 69 | function add(a, b) { 70 | // 👆 Notice we don't mention the datatypes of the return value. 71 | return a + b; 72 | } 73 | ``` 74 | 75 | ```java 76 | // Java 77 | String message = "Keep smiling! 😄"; // 👈 Notice we mention a datatype, String in this case. 78 | int happiness = 100; // 👈 Notice we mention a datatype, int in this case. 79 | 80 | int add(int a, int b) { // 👈 Notice we mention the datatype of the return value, int in this case. 81 | return(a+b); 82 | } 83 | ``` 84 | 85 | The type is associated at the run time value. This creates a huge ruckus for programmers 🤬! Here is where TypeScript comes to rescue. It is a strongly typed language and transplies the `TypeScript` code to JavaScript code. 86 | 87 | Read more about TypeScript [here](https://www.typescriptlang.org/docs). 88 | 89 | ✅ **Single-Threaded** 90 | 91 | JavaScript is a `single-threaded` language. So it can only do only **ONE** computation at a time. When a JavaScript. To combat this, JavaScript implements the concept of `Event Loops` 92 | 93 | ✅ **Synchronou**s 94 | 95 | JavaScript is `Synchronous`, this essentailly means that each code runs line-by-line. 96 | 97 | --- 98 | 99 | ```md 100 | Lets recapitulate 📝: 101 | 102 | ➡ JavaScript is a high-level, weakly typed, interpreted, synchronous, single-threaded and JIT programming language. 103 | 104 | ➡ To overcome its blocking feature it implements Event Loops. 105 | ``` 106 | 107 | Read more [here](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript). 108 | 109 | --- 110 | 111 | See also 112 | 113 | > ⚫ Event Loop. 🔁 😵 [ Read ▶ ](./event-loop.md) 114 | > ⚫ Closures [ Read ▶ ](./closures.md) 115 | -------------------------------------------------------------------------------- /notes/what-is-the-truth.md: -------------------------------------------------------------------------------- 1 | # **What is the Truth? 🤥** 2 | 3 | [Home](../README.md) / What is the Truth? 🤥 4 | 5 | --- 6 | 7 | ## Contents ✨ 8 | 9 | ➡ [Truthy and Falsy](#truthy-and-falsy) 10 | 11 | ➡ [Why Truthy & Falsy](#why-truthy-&-falsy) 12 | 13 | --- 14 | 15 | ## **Truthy and Falsy** 16 | 17 | In JavaScript when a value is encountered in a Boolean context - such as an `if` statement - it will be coerced into a boolean. If the result is `true` then the value is truthy and vice versa. 18 | 19 | Example: 20 | 21 | ```js 22 | // Truthy 23 | > true; // true 24 | > !! "hello"; // true 25 | > !! -1; // true (All numbers except 0 are true) 26 | > !! []; // true 27 | > !! {}; // true 28 | > !! function demo() {} // true 29 | 30 | // Falsy 31 | > false; // false 32 | > !! null; // false 33 | > !! undefined; // false 34 | > !! 0; // false 35 | > !! ""; // false 36 | ``` 37 | 38 | > If you’re unsure about a value, you can convert it using the logical `"!"` NOT operator twice `"!!"`. 39 | 40 | --- 41 | 42 | ## **Why Truthy & Falsy** 43 | 44 | Knowing what does a variable return helps the programmer to control the flow of the program. 45 | 46 | ```js 47 | function unicorns(name) { 48 | const unicon = name; 49 | if (unicorn) { 50 | return "Unicorns Exists!"; 51 | } else { 52 | return "Unicorns Don't Exists!"; 53 | } 54 | } 55 | 56 | console.log(unicorns("🦄")); // Unicorns Exists! 57 | console.log(unicorns()); // Unicorns Don't Exists 58 | ``` 59 | 60 | Above is a simple demostration about how the control can be handled using Truthy and Falsy. 61 | 62 | ```md 63 | Lets recapitulate 📝: 64 | 65 | ➡ Empty primitive values are false, where as objects is true. 66 | 67 | ➡ Truthy and Falsy are used to control the flow of the program. 68 | ``` 69 | 70 | --- 71 | 72 | See also: 73 | 74 | > ⚫ Promises 🤝 and Async/Await 🤯 [ Read ▶ ](./promises.md) 75 | > ⚫ Hoisting 🏴‍☠️ ? ...is this a Ship? 🤨 [ Read ▶ ](./hoisting.md) 76 | > ⚫ Event Loop. 🔁 😵 [ Read ▶ ](./event-loop.md) 77 | -------------------------------------------------------------------------------- /scripts/async-await.js: -------------------------------------------------------------------------------- 1 | const getVeggie = (name) => { 2 | const veggies = { 3 | mango: "🥭", 4 | apple: "🍎", 5 | banana: "🍌", 6 | avocado: "🥑", 7 | }; 8 | 9 | console.log("returned", veggies[name]); 10 | return veggies[name]; 11 | }; 12 | 13 | const getSalad = async () => { 14 | const mango = await getVeggie("mango"); 15 | const apple = await getVeggie("apple"); 16 | const avocado = await getVeggie("avocado"); 17 | const banana = await getVeggie("banana"); 18 | 19 | return [mango, apple, avocado, banana]; 20 | }; 21 | 22 | getSalad() 23 | .then((response) => console.log(response)) 24 | .catch((error) => console.log(error)); 25 | -------------------------------------------------------------------------------- /scripts/asynchronous-pro.js: -------------------------------------------------------------------------------- 1 | const delay = (time) => { 2 | return new Promise((resolve) => { 3 | setTimeout(resolve, time); 4 | }); 5 | }; 6 | 7 | let time = Date.now(); 8 | const log = () => console.log(`Elapsed: ${(Date.now() - time) / 1000}s`); 9 | 10 | const getVeggie = async (name) => { 11 | // Stop the Execution thread for 1s. 12 | 13 | await delay(1000); 14 | 15 | const veggies = { 16 | mango: "🥭", 17 | apple: "🍎", 18 | banana: "🍌", 19 | avocado: "🥑", 20 | }; 21 | 22 | console.log("returned", name); 23 | return veggies[name]; 24 | }; 25 | 26 | const getSalad = async () => { 27 | const mango = await getVeggie("mango"); 28 | const apple = await getVeggie("apple"); 29 | const avocado = await getVeggie("avocado"); 30 | const banana = await getVeggie("banana"); 31 | 32 | return [mango, apple, avocado, banana]; 33 | }; 34 | 35 | // getSalad().then((response) => console.log(response)); 36 | 37 | const getSaladFaster = async () => { 38 | const mango = getVeggie("mango"); 39 | const apple = getVeggie("apple"); 40 | const avocado = getVeggie("avocado"); 41 | const banana = getVeggie("banana"); 42 | 43 | return Promise.all([mango, apple, avocado, banana]); 44 | }; 45 | 46 | // getSaladFaster().then((response) => console.log(response)); 47 | 48 | // Note the time difference in execution between these two functions 49 | // Run them one by one 50 | getSalad().then(log); // ~4sec 51 | getSaladFaster().then(log); // ~1sec 52 | -------------------------------------------------------------------------------- /scripts/closures.js: -------------------------------------------------------------------------------- 1 | function outer(n) { 2 | let x = n; // persits in memory after outer is popped off the call stack 3 | 4 | function inner() { 5 | return x; 6 | } 7 | 8 | return inner; 9 | } 10 | 11 | // Creates the Closure. 12 | const closure = outer(1); 13 | 14 | // Operates within its context or lexical environment 15 | console.log(closure()); // 1 16 | 17 | // Here is an another example. 18 | 19 | function counter(x) { 20 | function increment(y) { 21 | return x + y; 22 | } 23 | 24 | return increment; 25 | } 26 | 27 | const incrementBy1 = counter(1); 28 | incrementBy1(1); // 2 29 | incrementBy1(10); // 11 30 | -------------------------------------------------------------------------------- /scripts/event-loop.js: -------------------------------------------------------------------------------- 1 | const first = () => console.log("First"); 2 | const second = () => setTimeout(() => console.log("Second"), 0); 3 | const third = () => console.log("Third"); 4 | 5 | first(); 6 | second(); 7 | third(); 8 | -------------------------------------------------------------------------------- /scripts/hoisting.js: -------------------------------------------------------------------------------- 1 | console.log(n); // Returns undefined, as only declaration was hoisted, no initialization has happened at this stage 2 | var n; // Declaration 3 | n = 5; // Initialization 4 | 5 | fun(); // works. 6 | 7 | function fun() { 8 | console.log("I work! ✨"); 9 | } 10 | -------------------------------------------------------------------------------- /scripts/promise.js: -------------------------------------------------------------------------------- 1 | const getFruit = (name) => { 2 | const fruits = { 3 | mango: "🥭", 4 | apple: "🍎", 5 | banana: "🍌", 6 | avocado: "🥑", 7 | }; 8 | 9 | let flag = fruits[name]; 10 | 11 | return new Promise((resolve, reject) => { 12 | if (flag) { 13 | resolve("Yay there is Fruit! 😄"); 14 | } else { 15 | reject("Sorry there's no Fruit 😔"); 16 | } 17 | }); 18 | }; 19 | 20 | getFruit("mango") 21 | .then((response) => console.log(response)) 22 | .catch((error) => console.log(error)); 23 | --------------------------------------------------------------------------------