├── README.md └── JS_Class_Part2 ├── functions ├── index.html └── index.js ├── callback_function ├── index.html └── index.js ├── callback_helll └── index.js └── promises └── index.js /README.md: -------------------------------------------------------------------------------- 1 |

Javascript-Advance

2 | 1. How JS works behind the scene -- Notes

3 | 2. To visualize how callback and event loop works
4 | -------------------------------------------------------------------------------- /JS_Class_Part2/functions/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | JS Task 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /JS_Class_Part2/callback_function/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | JS Task 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /JS_Class_Part2/callback_function/index.js: -------------------------------------------------------------------------------- 1 | // //What are callback function in JAVASCRIPT: 2 | // setTimeout(function(){ 3 | // console.log("Timer"); 4 | // }, 3000); 5 | 6 | // function x(y){ 7 | // console.log("This is X function"); 8 | // y(); 9 | // } 10 | 11 | // x(function y(){ 12 | // console.log("This is Y function"); 13 | // }) 14 | // // console.log("Wait"); 15 | 16 | // //In JS is synchronous and single threaded means it will execute 1 line at a time. 17 | // //Js has single call stack/ main thread. Everything excuted inside the page will executed through the callstack 18 | // // "SO" 19 | // //If any heavy operation will take more time to excute like (20- 30secs),by the time JS has only 1 call stack so it won't be able to execute anyother function in the code it will block the main thread/call stack called as blocking the main thread 20 | 21 | // //To avoid blocking the main thread -- we go for asynchronous behaviour just like we did with setTimeOut() 22 | // //setTimeOut will take the call back and will execute this piece of code somewhere else and it will empty the call stack and get out of the call stack. 23 | // //Using WebAPIs (setTimeOut) + callback = we can achieve the asynchronous behaviour. 24 | 25 | //Asynchronous code is always executed after the main thread 26 | //Never trust the delay given to the setTimeout function. You can only specify a minimum delay. Even if you set a 0 delay, your code could be executed much later. 27 | 28 | setTimeout(function () { 29 | console.log("I am an asynchronous message"); 30 | }); // You can omit the 0 31 | 32 | console.log("Test 1"); 33 | 34 | for (let i = 0; i < 10; ++i) { 35 | console.log(doSomeStuff()); 36 | } 37 | 38 | console.log("Test 2"); 39 | 40 | // The 'I am an asynchronous message' will be displayed when the main thread reach here 41 | 42 | function doSomeStuff() { 43 | return "Function doSomestuff"; 44 | } 45 | 46 | //setInterval 47 | //setInterval has the same behavior as setTimeout but the code is executed multiple times. 48 | //You have to call clearInterval to kill the timer. 49 | 50 | let counter = 0; 51 | 52 | let timer = setInterval(function () { 53 | console.log("I am an asynchronous message"); 54 | 55 | counter += 1; 56 | 57 | if (counter >= 5) { 58 | clearInterval(timer); 59 | } 60 | }, 1000); 61 | 62 | console.log("I am a synchronous message"); 63 | 64 | //With more and more asynchronous code and features in recent frameworks, we need something to manage it. Here comes our savior: the Promise class. 65 | //It is now the standard way to deal with asynchronous code 66 | -------------------------------------------------------------------------------- /JS_Class_Part2/functions/index.js: -------------------------------------------------------------------------------- 1 | //1.1 -- FUNCTION STATEMENT/ FUNCTION DECLARATION 2 | // funStatement(); // it created a memory and a function is assign to it. 3 | 4 | function funStatement(){ 5 | console.log("This is function statement also called as function declaration"); 6 | } 7 | funStatement(); 8 | 9 | //1.2 -- FUNCTION EXPRESSION 10 | //You can assign function to a variable. Here function will act like a value 11 | // functionExpression(); //it is created like a variable like any other variable, 12 | //it is assigned undefined initially until the code reaches to the actual funciton 13 | 14 | var funExpression = function(){ 15 | console.log("This is function Expression"); 16 | } 17 | funExpression(); 18 | 19 | //Difference between function statement and function expression 20 | //Major difference b/w two is Function Hoisting. 21 | //short intro to function hoisting -- if we call function statement before declaration it will show an output 22 | //successfully but in we call function expression before function it will throw an Error 23 | //as it will consider it as a variable 24 | 25 | //1.3 -- ANONYMOUS FUNCTION: 26 | //function without a name is called an anonmyous function 27 | 28 | // function (){ 29 | // console.log("Anonymous Function"); 30 | // }//this will result an error -- invalid syntax 31 | 32 | //So what are the advantages of anonymous functions 33 | //Anonymous functions are used where functions are used as a value. 34 | //Means you can assign function to a variable and eventually it will become function expression, where function is an anonmyous function but in function statement we cannot use an anonymous funcition 35 | 36 | //1.4 -- NAMED FUNCTION EXPRESSION: 37 | //Expression + Named function = Named function expression 38 | 39 | var namedFun = function xyz(){ 40 | console.log("This is Named function expression"); 41 | // console.log(xyz); 42 | } 43 | namedFun(); 44 | // xyz(); //will give an error -- b/c this name is local variable and has local scope here and can access xyz inside a function. 45 | 46 | 47 | //1.5 -- Difference b/w parameter and arguments: DIY 48 | 49 | 50 | //1.6 -- FIRST CLASS FUNCTION 51 | //The ability of function to be used as a value and can be passed this as an argument to another function and can be returned from the function is called as first class function. 52 | //First class function = first class citizens (refer by this in some books and articles) 53 | 54 | //Call back Function 55 | function value(){ 56 | console.log("Function 1"); 57 | // arg(); 58 | 59 | } 60 | var arg = function(){ 61 | console.log("Function 2"); 62 | } 63 | value(arg); 64 | 65 | -------------------------------------------------------------------------------- /JS_Class_Part2/callback_helll/index.js: -------------------------------------------------------------------------------- 1 | //Concept we will cover: 2 | //1-- Synchronous behaviour and callstack 3 | //2-- Role of callbacks 4 | //3-- Problem 1: Callback Hell 5 | //4-- Probelm 2: Inversion of Control 6 | 7 | //1-- Synchronous behaviour and callstack: 8 | //As we know JS is synchronous single threaded language and it has one callstack and can do single operation at a time 9 | //Callstack in Javascript: The call stack is used by JavaScript to keep track of multiple function calls. It is like a real stack in data structures where data can be pushed and popped and follows the Last In First Out (LIFO) principle. We use call stack for memorizing which function is running right now. 10 | 11 | //2-- Role of callbacks: 12 | //The question arises here is what if we need to execute any function after some certain delay? How can we perform this delay function as callstack doesnot wait and it keep executing whatever comes inside it, and there is no question on blocking the main thread. 13 | //So to tackle this problem, callbacks came into play: Callbacks used to be the main way asynchronous functions were implemented in JavaScript. A callback is just a function that's passed into another function, with the expectation that the callback will be called at the appropriate time. 14 | 15 | //3-- Problem 1: Callback Hell: Callback hell is nested callbacks stacked below one another forming a pyramid structure. Every callback depends/waits for previous callback, thereby making a pyramid structure that effects the readibility and maintability of the code. 16 | //Example: Ecommerce Website cart operation depended on one another 17 | //1. Create Order 18 | //2. Payment 19 | //3. Show Payment Summary 20 | //4. Update Wallet 21 | 22 | const cart = ["shirts", "jackets", "shoes"]; //just an example for understanding 23 | 24 | api.CreateOrder(cart, function () { 25 | api.proceedToPayment(function () { 26 | api.showOrderSummary(function () { 27 | api.updateWallet(); 28 | }); 29 | }); 30 | }); 31 | 32 | //One callback inside other callback inside another API, make this callback hell and our code grows horizontally instead of vertical which is called pyramid structure or pyramid of doom, which makes difficult in code maintainability and readability. 33 | //Pyramid Doom: 34 | job1(function () { 35 | doSomething1(); 36 | 37 | job2(function () { 38 | doSomething2(); 39 | 40 | job3(function () { 41 | doSomething3(); 42 | 43 | job4(function () { 44 | doSomething4(); 45 | }); 46 | }); 47 | }); 48 | }); 49 | 50 | //4-- Problem 2: Inversion of control 51 | //It's like we lose the control of our code when using callbacks => Inversion of control is the notion of having code under your control in one part of program and then handing control over to a callback in another part of the program 52 | 53 | const cart2 = ["shirts", "jackets", "shoes"]; //just an example for understanding 54 | 55 | api.CreateOrder(cart, function () { 56 | api.proceedToPayment(); 57 | }); 58 | 59 | //Here proceedToPayment() method relies on CreateOrder() => we can only proceedToPayment() once we CreateOrder() this is dependency of one function into another. What if, for any reason method 1 could not initiate the dependent method or initiate it twice 60 | 61 | //To visualize how callback and event loop works: https://wesbos.com/javascript/12-advanced-flow-control/66-the-event-loop-and-callback-hell 62 | -------------------------------------------------------------------------------- /JS_Class_Part2/promises/index.js: -------------------------------------------------------------------------------- 1 | //Topics we will cover 2 | //1-- Before and After Promises 3 | //2-- Difference between Callback and Promises 4 | //3-- State of Promises 5 | //4-- Promise Chaining 6 | 7 | //DEFINITON OF PROMISE: 8 | //A promise is an object representing the eventual completion or failure of an asynchronous operation. 9 | //Promsie also refer as a placeholder that will be filled later with a value. So promise object is a placeholder for a certain period of time until we recieve a value from a async function. 10 | //Promises also refer as a container for a future value. 11 | 12 | //1.1-- Before Promises: 13 | const cart = ["Shirts", "joggers", "jackets"]; 14 | 15 | createOrder(cart, function () { 16 | proceedToPayment(orderId); 17 | }); 18 | 19 | //Now here API is responsible to create an order and then call our callback function back once the order is created with orderId. 20 | //This was a method we used to handle our async function with callback methods. 21 | // "BUT" 22 | //Here is the issue of inversion of control with this code. What our API never call our callback function or call it twice due to any reason? So this is not reliable to giving control some part of your program to some other code which we are not aware of. 23 | //To handle it Promises came into play 24 | 25 | //Que: What are promises and how does it works? 26 | //1.2-- After Promises: 27 | const promise = createOrder(cart); //async function 28 | 29 | //When JS engine execute above line, createOrder API will return an empty object {} which is called promise -- and program start executing other functions. 30 | //After certain delay when async operation is performed it return data to an empty object/promise automatically. 31 | //Now we can attach our promise object to other callback functions using keyword "then". 32 | 33 | //promise.then(inside it we have our callback function) 34 | promise.then(function (orderId) { 35 | proceedToPayment(orderId); 36 | }); 37 | 38 | //Once our createOrder return a value to our promise then callback function attach to our promise will be automatically called. 39 | //2-- Difference between callback and promises 40 | //2.1: In callback we pass one function to another whereas in promises we attach a callback function to promise object. 41 | //2.2: In callback we have to relie on other code to call our callback fuction back and we hand over control to other program whereas in promises our callback functions executed automatically as soon as the promises object get the data from the async function and the control of program is in our hand. 42 | 43 | //3-- States of Promises: 44 | //We have 3 states of promises i.e pending, fullfilled, and rejected 45 | 46 | //Note: Promises objects are immutable that nobody can change what's inside the object of promise. 47 | 48 | //4-- Promise chaining: 49 | //Promise resolve the issue of inversion of control but what about issue of callback hell? 50 | //In callback hell we call functions one after another: 51 | 52 | createOrder(cart, function () { 53 | proceedToPayment(orderId, function (paymentInfo) { 54 | showOrderSummary(paymentInfo, function () { 55 | updateWallet(); 56 | }); 57 | }); 58 | }); //pyramid doom 59 | 60 | //We transforming the upper function using promise chaining 61 | createOrder(cart) 62 | .then(function (orderId) { 63 | return proceedToPayment(orderId); //return keyword is important while chaining promise 64 | }) 65 | .then(function (paymentInfo) { 66 | return showOrderSummary(paymentInfo); 67 | }) 68 | .then(function (paymentInfo) { 69 | return updateWallet(paymentInfo); 70 | }); 71 | 72 | //Create promise: 73 | //resolve and reject are function provided by JS 74 | //resolve -- when status is successful 75 | //reject -- when status is failed 76 | var pr = new Promise(function (resolve, reject) { 77 | //new promise is created 78 | setTimeout(function () { 79 | resolve("hello world"); 80 | }, 2000); 81 | }); 82 | 83 | pr.then(function (data) { 84 | console.log(data); 85 | }); 86 | 87 | //Multiple callback functions: 88 | var promise1 = new Promise(function (resolve, reject) { 89 | setTimeout(function () { 90 | resolve("hello world"); 91 | }, 2000); 92 | }); 93 | 94 | promise1.then(function (data) { 95 | console.log(data + " 1"); 96 | }); 97 | 98 | promise1.then(function (data) { 99 | console.log(data + " 2"); 100 | }); 101 | 102 | promise1.then(function (data) { 103 | console.log(data + " 3"); 104 | }); 105 | 106 | //When an error happens: 107 | var promise2 = new Promise(function (resolve, reject) { 108 | setTimeout(function () { 109 | reject("We are all going to die"); 110 | }, 2000); 111 | }); 112 | 113 | promise2.then( 114 | function success(data) { 115 | console.log(data); 116 | }, 117 | function error(data) { 118 | console.error(data); 119 | } 120 | ); 121 | 122 | //When an error happens with multiple callbacks: 123 | var promise3 = new Promise(function (resolve, reject) { 124 | setTimeout(function () { 125 | reject("We are all going to die"); 126 | }, 2000); 127 | }); 128 | 129 | promise3.then( 130 | function success(data) { 131 | console.log(data + " 1"); 132 | }, 133 | function error(data) { 134 | console.error(data + " 1"); 135 | } 136 | ); 137 | 138 | promise3.then( 139 | function success(data) { 140 | console.log(data + " 2"); 141 | }, 142 | function error(data) { 143 | console.error(data + " 2"); 144 | } 145 | ); 146 | 147 | promise3.then( 148 | function success(data) { 149 | console.log(data + " 3"); 150 | }, 151 | function error(data) { 152 | console.error(data + " 3"); 153 | } 154 | ); 155 | 156 | //catch() method: 157 | // Example 1 158 | let promise3 = request(); 159 | 160 | promise3.then( 161 | function (data) { 162 | console.log(data); 163 | }, 164 | function (error) { 165 | console.error(error); 166 | } 167 | ); 168 | 169 | // Example 2 170 | let promise3 = request(); 171 | 172 | promise3 173 | 174 | .then(function (data) { 175 | console.log(data); 176 | }) 177 | 178 | .catch(function (error) { 179 | console.error(data); 180 | }); 181 | 182 | //In the first example, we call then with a success callback and an error callback. 183 | //In the second example, we call then with a success callback and after that we call catch with an error callback. 184 | //The difference is in the promise returned by the then function. 185 | //In the second example, you are not calling catch on the original promise, you call catch on the promise returned by then. 186 | //If a then has no error callback provided, it will not stop on a rejected promise. So the promise will end in the catch. 187 | --------------------------------------------------------------------------------