├── Callback ├── robinCallback.png └── README.md ├── SyncAndAsync ├── syncCallStack.png ├── asyncWithSetTimeout.png ├── asyncWithSetTimeoutAndPromise.png └── README.md ├── ReactSuspense ├── fetchOnRender.png ├── fetchThenRender.png ├── reactSuspenseWithErrorboundary.png └── README.md ├── AsyncAndAwait └── README.md ├── CallbackHell └── README.md ├── ConcurrentReact └── README.md ├── Promise └── README.md ├── README.md ├── ReactServerComponents └── README.md ├── DebounceVsThrottle └── README.md ├── PWA └── README.md ├── ReactHooks └── README.md ├── ProgrammingParadigms └── README.md ├── PromiseChain └── README.md ├── PromiseAPIs └── README.md └── OopsConcepts └── README.md /Callback/robinCallback.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NagarjunShroff/Front-end-roadmap/HEAD/Callback/robinCallback.png -------------------------------------------------------------------------------- /SyncAndAsync/syncCallStack.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NagarjunShroff/Front-end-roadmap/HEAD/SyncAndAsync/syncCallStack.png -------------------------------------------------------------------------------- /ReactSuspense/fetchOnRender.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NagarjunShroff/Front-end-roadmap/HEAD/ReactSuspense/fetchOnRender.png -------------------------------------------------------------------------------- /ReactSuspense/fetchThenRender.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NagarjunShroff/Front-end-roadmap/HEAD/ReactSuspense/fetchThenRender.png -------------------------------------------------------------------------------- /SyncAndAsync/asyncWithSetTimeout.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NagarjunShroff/Front-end-roadmap/HEAD/SyncAndAsync/asyncWithSetTimeout.png -------------------------------------------------------------------------------- /SyncAndAsync/asyncWithSetTimeoutAndPromise.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NagarjunShroff/Front-end-roadmap/HEAD/SyncAndAsync/asyncWithSetTimeoutAndPromise.png -------------------------------------------------------------------------------- /ReactSuspense/reactSuspenseWithErrorboundary.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NagarjunShroff/Front-end-roadmap/HEAD/ReactSuspense/reactSuspenseWithErrorboundary.png -------------------------------------------------------------------------------- /Callback/README.md: -------------------------------------------------------------------------------- 1 | # Callback 2 | 3 | Callback is a function which is to be executed after another function has finished execution. - Great notification mechanism. 4 | 5 | example: 6 | ![Robin pizza](robinCallback.png) 7 | 8 | ``` 9 | // Robin's end on clicking order pizza button 10 | orderPizza("veg", "cheese barbeque", (msg) => console.log(msg)); 11 | 12 | // PizzaHub's end 13 | 14 | const orderPizza = (type, name, callback) => { 15 | console.log(`Pizza ${type} ${name} is ordered!`); 16 | 17 | setTimeout(() => { 18 | const msg = `Pizza ${type} ${name} is ready!!!`; 19 | callback(msg); 20 | }, 3000); 21 | } 22 | 23 | Output: 24 | Pizza veg cheese barbeque is ordered! 25 | 26 | (after 3 secs) 27 | Pizza veg cheese barbeque is ready!!! 28 | 29 | ``` -------------------------------------------------------------------------------- /AsyncAndAwait/README.md: -------------------------------------------------------------------------------- 1 | # Async and Await 2 | 3 | - async keyword is used to return a promise. 4 | - await keyword is used to wait and handle a promise. 5 | 6 | Example: 7 | ``` 8 | const validateUser = (userId, password) => { 9 | return new Promise((resolve, reject) => { 10 | if(userId && password) { 11 | resolve("Authenticated!"); 12 | } else { 13 | reject({message: "userId and password is missing"}); 14 | } 15 | }); 16 | }; 17 | 18 | const app = async () => { 19 | const data = { 20 | userId: 123, 21 | password: 456 22 | }; 23 | 24 | try { 25 | const response = await validateUser(data.userId, data.password); 26 | console.log(response); 27 | } catch(e) { 28 | console.log(e.message); 29 | } 30 | }; 31 | 32 | app(); 33 | 34 | ``` 35 | -------------------------------------------------------------------------------- /CallbackHell/README.md: -------------------------------------------------------------------------------- 1 | # Callback hell - Pyramid of Doom 2 | Callback hell is a phenomenon where a callback is called inside another callback. it is nesting of multiple callback with in a function. it is also reffered as "Pyramid of Doom". 3 | 4 | Example: 5 | ``` 6 | function print(i){ 7 | window.alert("This is call number", i); 8 | }; 9 | 10 | function fun1(callback) { 11 | setTimeout(() => { 12 | let i = 1; 13 | callback(i); 14 | i++; 15 | 16 | setTimeout(() => { 17 | callback(i); 18 | i++; 19 | 20 | setTimeout(() => { 21 | callback(i); 22 | i++; 23 | 24 | setTimeout(() => { 25 | callback(i); 26 | i++; 27 | 28 | setTimeout(() => { 29 | callback(i); 30 | i++; 31 | }, 800); 32 | }, 700); 33 | }, 500); 34 | }, 300); 35 | }, 100); 36 | }; 37 | 38 | fun1(print); 39 | 40 | ``` -------------------------------------------------------------------------------- /ConcurrentReact/README.md: -------------------------------------------------------------------------------- 1 | # Concurrent React 2 | 3 | - What is Concurrent React? 4 | 5 | Its new behind-the-scenes mechanism that enables React to prepare multiple versions of your UI at the same time. 6 | 7 | A key property of Concurrent React is that rendering is interruptible. This is introduced in React v18.0.0, before this version updates are rendered in a single, uninterrupted, synchronous transaction. With synchronous rendering, once the updates starts rendering, nothing can interrupt until the user see the results on the screen. 8 | 9 | In a concurrent render, this was not always the case. React may start rendering an update, stops it in the middle ,then continue later. it may even abandon an in-progress render altogether. React guarantees that the UI will appear consistent even if a render is interrupted.To do this, it waits to perform DOM mutations until the end, once the entire tree has been evalutated. With this capability, React can prepare new screens in the background without blocking the main thread. This means UI can respond immediately to the user inputs even if it is in the middle of large rendering task,creating a fluid user experience. 10 | 11 | Another example is reusable state. Concurrent React can remove the sections of the UI from the screen, then add them back later while reusing the previous state. For example, when the user tabs away from the screen and back, React should be able to restore the previous screen in the same state as it was in before. -------------------------------------------------------------------------------- /Promise/README.md: -------------------------------------------------------------------------------- 1 | # Promise - How to Resolve or Reject a Promise 2 | 3 | Promise: An Object represents an eventual completion or failure of an asynchronous operations and its resulting value. 4 | 5 | Example: 6 | ``` 7 | Resolved promise. 8 | 9 | const promise1 = new Promise(function(resolve, reject){ 10 | resolve('Water'); 11 | }); 12 | 13 | Rejected promise. 14 | 15 | const promise2 = new Promise(function(resolve, reject){ 16 | reject(new Error("Disaster!")); 17 | }); 18 | ``` 19 | 20 | Promise takes an exector function as parameter which can have deciding factor to resolve or reject it. 21 | 22 | - Promise has 3 different states. 23 | 1. pending: When the exection starts. 24 | 2. fullfilled: When the promise gets resolved. 25 | 3. rejected: When the promise gets rejected. 26 | 27 | - Promise can have 3 different values based on the state. 28 | 1. undefined: When promise is in pending state, not fulfilled or rejected. 29 | 2. value: When the promise gets resolved. 30 | 3. error: When the promise gets rejected. 31 | 32 | - Promise provides 3 method handlers. 33 | 1. .then() 34 | 2. .catch() 35 | 3. .finally() 36 | 37 | Example: 38 | ``` 39 | const promise = new Promise(function(resolve, reject){ 40 | resolve('Water'); 41 | //reject(new Error("Jack fell down")); 42 | }); 43 | 44 | const consumer = promise.then((result) => 45 | console.log(`Cooking with ${result}.`) 46 | ).catch((error) => 47 | console.log(`OMG ${error.message}.`)); 48 | 49 | consumer(); 50 | 51 | Output: 52 | if promise gets resolved the output will be: Cooking with Water. 53 | if promise gets rejected the output will be: OMG Jack fell down. 54 | 55 | ``` -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Front-end-roadmap 2 | 3 | This repository is for learning the Front-end concepts. 4 | 5 | 1. [Concurrent React](https://github.com/NagarjunShroff/Front-end-roadmap/blob/master/ConcurrentReact/README.md) 6 | 2. [React Suspense](https://github.com/NagarjunShroff/Front-end-roadmap/blob/master/ReactSuspense/README.md) 7 | 3. [React Server Components](https://github.com/NagarjunShroff/Front-end-roadmap/blob/master/ReactServerComponents/README.md) 8 | 4. [JavaScript Synchronous and Asynchronous programing](https://github.com/NagarjunShroff/Front-end-roadmap/blob/master/SyncAndAsync/README.md) 9 | 5. [Promise - How to Resolve or Reject a Promise](https://github.com/NagarjunShroff/Front-end-roadmap/blob/master/Promise/README.md) 10 | 6. [Callback](https://github.com/NagarjunShroff/Front-end-roadmap/blob/master/Callback/README.md) 11 | 7. [Promise Chain](https://github.com/NagarjunShroff/Front-end-roadmap/blob/master/PromiseChain/README.md) 12 | 8. [Callback hell - Pyramid of Doom](https://github.com/NagarjunShroff/Front-end-roadmap/blob/master/CallbackHell/README.md) 13 | 8. [Async and Await](https://github.com/NagarjunShroff/Front-end-roadmap/blob/master/AsyncAndAwait/README.md) 14 | 10. [Promise APIs](https://github.com/NagarjunShroff/Front-end-roadmap/blob/master/PromiseAPIs/README.md) 15 | 11. [React Hooks](https://github.com/NagarjunShroff/Front-end-roadmap/blob/master/ReactHooks/README.md) 16 | 12. [Programming Paradigms](https://github.com/NagarjunShroff/Front-end-roadmap/blob/master/ProgrammingParadigms/README.md) 17 | 13. [JavaScript OOPS concepts](https://github.com/NagarjunShroff/Front-end-roadmap/blob/master/OopsConcepts/README.md) 18 | 14. [Debounce Vs Throttle](https://github.com/NagarjunShroff/Front-end-roadmap/blob/master/DebounceVsThrottle/README.md) 19 | 15. [PWA](https://github.com/NagarjunShroff/Front-end-roadmap/blob/master/PWA/README.md) -------------------------------------------------------------------------------- /ReactSuspense/README.md: -------------------------------------------------------------------------------- 1 | # React Suspense 2 | 3 | Before deep diving into React Suspense lets know about Data fetching patterns 4 | 5 | - Data fetching patterns 6 | a. Fetch on Render: 7 | This is most used way of data fetching. 8 | ![Fetch on render](./fetchOnRender.png) 9 | 10 | Problem: Consider parent and child components makes network calls on mounting phase, if the network call in the parent component fails during the component mount, it never allows the child component to render( Network waterfall ). 11 | 12 | b. Fetch then Render: 13 | ![Fetch then render](./fetchThenRender.png) 14 | Here we solve Network waterfall issue. 15 | 16 | Problem: Consider if the Parent component makes multiple network calls, children components render will wait till all the network calls to be resolved. 17 | 18 | c. Render while fetch: React Suspense. 19 | Before getting into the React Suspense lets understand what is Imperative and Declarive Programing. 20 | 21 | Imperative: You tell what needs to be done and how it needs to be done. 22 | example: Java, C, Pascal etc.. 23 | 24 | Declarative: You tell the program that what needs to be done in declarative way and the program will take care of it. 25 | example: React - you dont need to worry about DOM manipulations. React Suspense is another example, ML 26 | 27 | React Suspense: 28 | a. We dont need to matain loading state. 29 | b. We dont need to make network call on the component mount using useEffect. 30 | 31 | Syntax: 32 | ``` 33 | Loading...

}> 34 | 35 |
36 | ``` 37 | Suspense will show the "Loading..." on the UI till the YourComponent network calls get resolved. Once it is resolved it will show the corresponding response(depending on the how you are rendering in YourComponent). 38 | 39 | Error boundary: 40 | In the above code snippet if the network call of the YourComponent fails with the error, to display any error response, we can use the Error boundary. 41 | 42 | We can have a generic error page cin the project and use it to display when network calls fails or throws error. 43 | 44 | We can use 3rd party library "react-error-boundary" in the project to do the same. 45 | 46 | Suspense will always reach out to the nearer error boundary when the component's network fails or throws error. 47 | ![React Suspense with Error boundary](./reactSuspenseWithErrorboundary.png) 48 | 49 | project: https://github.com/NagarjunShroff/react-suspense -------------------------------------------------------------------------------- /ReactServerComponents/README.md: -------------------------------------------------------------------------------- 1 | # React Server Components 2 | 3 | React Server Compoenents (RSC) allows you to write the UI that can be rendered and optionally cached on the server. 4 | 5 | - What are all the thing to be keep in mind while writing RSC 6 | 7 | Basically if the components needs only data to display and does not need any user interactions, state management, Effect management, browser API's - these components are best suitable to be Server Components. 8 | 9 | - Advantages 10 | 1. Needs backend access without roundtrip (No latency) 11 | 2. No waterfalls. 12 | 3. Automatic code splitting. 13 | 4. Zero bundle size. 14 | 5. An RSC can import and render the client compoenent, but reverse is not possible. However you can pass the RSC as props to client component. 15 | 6. Use client components as much as possible at the leaf level and server components in the root level. 16 | 17 | - Limitations 18 | Server components does not have access to event handlers like click handler, client states and effects. 19 | 20 | - Importance of Server Compoenents 21 | 1. Data fetching: 22 | Server Components allows you to move the data fetching logic to the server (nearer to the data source), so it takes less time to resolve the request. This will improve the performance by reducing the time. 23 | 24 | 2. Security: 25 | Server Components allows you to move the sensitive data or logic to deal with tokens and API keys to server without taking the risk of exposing them to the client. 26 | 27 | 3. Caching: 28 | By rendering on the server, results can be cached and reused on subsequest request and across users, so that it improves the performace by not querying frequesntly. 29 | 30 | 4. Bundle size: 31 | By rendering on the server, all the dependencies does not to be dowloaded in the client side which make the page to render faster. 32 | 33 | 5. Initial page lod and First Contentful Paint (FCP): 34 | Server components allows you to generate the HTML on the server and make it availble for the user immediately, without waiting for the client to download, parse and execute the javaScrpt to render the page. 35 | 36 | 6. Search Engine Optimization and Social Networking Sharebility: 37 | Rendered HTMl on the server can be used by the search engine bots to idex the page and social network bots to create social card preview for the page. 38 | 39 | 7. Streaming: 40 | Server components allows you to split the rendering work into chunks and stream it to client as in when it is ready. This allows the user to see certain parts of the UI without waiting for the entire UI to be ready on the server. -------------------------------------------------------------------------------- /DebounceVsThrottle/README.md: -------------------------------------------------------------------------------- 1 | # Debounce Vs Throttle 2 | 3 | - Debounce: 4 | 5 | Debounce monitors the delay between the user actions and execute the callback when the delay exceeds the threshold value set by the developer. Continous user actions will subsequently delay the execution of the callback. 6 | 7 | Debounce is most suitable for control events like typing or button clicks. 8 | 9 | Example: 10 | 11 | ``` 12 | const searchBarDom = document.getElementById("search-bar"); 13 | let numberOfKeyPresses = 0; 14 | let numberOfApiCalls = 0; 15 | 16 | const getResults = debounce(() => { 17 | numberOfApiCalls += 1; 18 | console.log(`Number of API calls: ${numberOfApiCalls}`); 19 | }, 1000); 20 | 21 | searchBarDom.addEventListener("input", function(e){ 22 | numberOfKeyPresses += 1; 23 | console.log(`Search Keyword: ${e.target.value}`); 24 | console.log(`Number of Key Presses: ${numberOfKeyPresses}`); 25 | getResults(); 26 | }); 27 | 28 | function debounce(callback, delay){ 29 | let timer; 30 | return (...args){ 31 | clearTimeout(timer); 32 | timer = setTimeout(() => callback(...args), delay); 33 | }; 34 | }; 35 | 36 | HTML: 37 | 38 | 39 | 40 | ``` 41 | - Throttle: 42 | 43 | Throttle uses the delay to execute the callback at regular intervals until the event trigger is active. It doesnt delay the execution of the callback for a significant period like debounce. 44 | 45 | Throttle is most suitable for continous event actions like resizing and scrolling. 46 | 47 | ``` 48 | const searchBarDom = document.getElementById("search-bar"); 49 | let numberOfKeyPresses = 0; 50 | let numberOfApiCalls = 0; 51 | 52 | const getResults = throttle(() => { 53 | numberOfApiCalls += 1; 54 | console.log(`Number of API calls: ${numberOfApiCalls}`); 55 | }, 1000); 56 | 57 | searchBarDom.addEventListener("input", function(e){ 58 | numberOfKeyPresses += 1; 59 | console.log(`Search Keyword: ${e.target.value}`); 60 | console.log(`Number of Key Presses: ${numberKeyPresses}`); 61 | getResults(); 62 | }); 63 | 64 | function throttle(callback, delay){ 65 | let shouldWait = false; 66 | 67 | return (...args){ 68 | if (shouldWait) 69 | return; 70 | callback(...args); 71 | shouldWait = true; 72 | setTimeout(() => shouldWait = false, delay); 73 | }; 74 | }; 75 | 76 | HTML: 77 | 78 | 79 | 80 | ``` 81 | project: https://github.com/NagarjunShroff/debounce-and-throttle -------------------------------------------------------------------------------- /PWA/README.md: -------------------------------------------------------------------------------- 1 | # Progressive Web Application - PWA 2 | 3 | PWA is an application built with modern web technologies to provide the platform-specific application user experience from the same code base. 4 | 5 | Native Applications(Platform-specific apps) ios and andriod: 6 | - Installable 7 | - Automatic updates 8 | - High Availablity(Offline) 9 | - App Store 10 | - Capabilities 11 | 12 | Web applications: 13 | - Single codebase 14 | - Highly distributed 15 | 16 | Servce Workers: 17 | 18 | Service workers are one of the pillars of PWA, helping with caching, offline availablity and fast loading. 19 | 20 | Service workers are javaScript code that runs as a separate thread from the main thread. This acts as proxy server between the client and server. In PWA Client is browser and server is data source. 21 | 22 | Service Workers are specialized in intercepting network requests and perform apropriate actions like serving the data from the cache store(Cache Storage API) when it is offline or from the server when it is online. 23 | 24 | Before applying the service worker, you should register the service worker in your PWA. Once registration is done, service worker gets downloaded on the client to start the installation and activation process. 25 | 26 | Manifest file: (manifest.json) 27 | 28 | PWA needs meta information such as name, description, icons and launch mode. 29 | 30 | All the details you have provided in the manifest.json will be used in moblie app installation. 31 | 32 | You can see the details in dev tools - Application 33 | 34 | 35 | Caching: 36 | Progressive Web Apps are known for offering speed and high availability on users mobile devices. So much so, in fact, that they can work completely or partially in offline mode. Caching helps achieve that, which makes the gap between a PWA and a native mobile app smaller. 37 | 38 | The service worker uses Cache Storage API to interact with the cache and manage assets as appropriate. As a developer of the PWA, you must decide what you want to cache and what your caching strategy should be. 39 | 40 | For example, you may want to cache the following assets: 41 | 42 | All the static images 43 | 44 | CSS Styles 45 | 46 | All static fonts 47 | 48 | Static data that comes from a JSON file 49 | 50 | The entry-point index.html page or any other pages 51 | 52 | JavaScript files that serve the business logic 53 | 54 | You must also consider the space on the user’s mobile device before considering what you want to cache. 55 | 56 | You can explore and adapt various caching strategies, based on the application’s use cases. Here are the five most popular strategies to explore: 57 | 58 | 1. Cache only 59 | 60 | 2. Network only 61 | 62 | 3. Stale-While-Revalidate 63 | 64 | 4. Cache first, then Network 65 | 66 | 5. The network first, then Cache 67 | -------------------------------------------------------------------------------- /ReactHooks/README.md: -------------------------------------------------------------------------------- 1 | # React Hooks 2 | 3 | 1. State Hooks: 4 | - useState: lets you to declare a state variable and you can update it directly. 5 | 6 | - useReducer: lets you to declare a state variable with the update logic inside a reducer function. 7 | 8 | 2. Context Hook: 9 | - useContext: lets you to pass the information from a component to its child components(at any level) without using props. 10 | 11 | 3. Ref Hooks: 12 | - useRef: This lets you hold the information and it is not used for rendering. Mostly use to hold the DOM node. 13 | unlike useState, updating the ref does not re-render the component. 14 | 15 | - useImperativeHandle: This lets you to customise the ref exposed by your component. 16 | 17 | 4. Effect Hooks: 18 | - useEffect: This lets you to connect to and synchronous with external system. This includes dealing with network, browser DOM, animations, Widgets developed using other UI library and any other non-react code. 19 | 20 | Effects are an "escape hatch" from the React paradigm. Dont use effects for orchestrate the data flow in your application. If you are not interacting with external systems, you might need not to use effects. 21 | 22 | - useLayoutEffect: fires before the browser repaints the screen. you can calculate the layout here. 23 | 24 | -useInsertionEffect: fires before React does changes to the DOM. Libraries can insert the dynamic CSS here. 25 | 26 | 5. Performance Hooks: 27 | A common way to improove the performace of the re-rendering by avoiding the unnecessary work. You can tell react to reuse the cached results of an expensive calculations or skip the re-rendering if the data has not been changed since the last render. 28 | 29 | - useMemo: lets you to cached the results of an expensive calculations. 30 | 31 | - useCallback: lets you to cache the function definaton before passing it to optimized component. 32 | 33 | Sometimes you can avoid re-rendering as the screen needs to be updated. In that case you can improve the preformance by separting out the blocking updates that are synchronous from the non-blocking updates that does not need to block the user interface. 34 | 35 | for better rendering, you can use one of the bleow hooks, 36 | 37 | - useTransistion: lets you to mark the state transition as non-blocking and allow other updates to interrupt it. 38 | 39 | -useDefferedValue: lets you to deffer updating the non-critical part of UI and lets other important part to update first. 40 | 41 | 6. Resource Hook: 42 | Resource can be accessed by a component without keeping them in their state. 43 | 44 | - use: lets you to read the value from the resource like a promise or context. 45 | 46 | 7. Other Hooks: 47 | These are meant for library authours and not being used in application. 48 | 49 | - useDebugvalue: lets to customize the lable REact devTools display for your custom hook. 50 | 51 | - useId: lets a compoenent to have associated unique ID with itself. 52 | 53 | - useSyncExternalStore: lets a component to subscribe to an external store. 54 | 55 | 56 | -------------------------------------------------------------------------------- /SyncAndAsync/README.md: -------------------------------------------------------------------------------- 1 | # JavaScript Synchronous and Asynchronous programing 2 | 3 | - JavaScript: An Single threaded, Non-blocking, Asynchronous, Concurrent programming language with lots of flexibility. 4 | 5 | - Synchronous: Everything what happens inside the Function Execution Stack(Call Stack) is sequential. This is the synchronous part of JavaScript. 6 | 7 | JavaScript's single thread make sure taking care of everything inside Function Execution Stack before it looks into anything else. 8 | 9 | Example 10 | ``` 11 | function f1() { 12 | console.log("f1"); 13 | }; 14 | 15 | function f2(){ 16 | console.log("f2"); 17 | }; 18 | 19 | function f3(){ 20 | console.log("f3"); 21 | } 22 | 23 | f1(); 24 | f2(); 25 | f3(); 26 | 27 | Output: 28 | f1 29 | f2 30 | f3 31 | ``` 32 | ![Call Stack](syncCallStack.png) 33 | 34 | - Asynchronous: Not occuring at the same point. 35 | 36 | - Usecases for Asychronous programing 37 | 1. Fetching data from the server. 38 | 2. Want to execute something with a delay. 39 | 3. Want to execute something after an event. 40 | 41 | - Majority of the time asychronous programing comes into picture 42 | 1. Browser APIs or Web APIs 43 | 2. Promises - An unique javascript object that allows to do asynchronous operations. 44 | 45 | Example 1: 46 | ``` 47 | function f1(){ 48 | console.log("f1"); 49 | }; 50 | 51 | function f2(){ 52 | console.log("f2"); 53 | }; 54 | 55 | function main(){ 56 | console.log("main"); 57 | 58 | setTimeout(f1, 0); 59 | 60 | f2(); 61 | } 62 | 63 | main(); 64 | 65 | Output: 66 | main 67 | f2 68 | f1 69 | ``` 70 | 1. Main() gets invoked and "main" will get printed. 71 | 2. SetTimeout is the Browser API, f1() call back will gets into call queue. 72 | 3. f2() gets in the stack and gets executes - which prints "f2". 73 | 4. Nothing in the execution stack, event loop indentifies and moves f1() callback to the execution stack and that gets executed. 74 | 75 | ![Asynchronous with setTimeout](asyncWithSetTimeout.png) 76 | 77 | Example 2: 78 | ``` 79 | function f1(){ 80 | console.log("f1"); 81 | }; 82 | 83 | function f2(){ 84 | console.log("f2"); 85 | }; 86 | 87 | function main(){ 88 | console.log("main"); 89 | 90 | setTimeout(f1, 0); 91 | 92 | new Promise(function(resolve, reject){ 93 | console.log("I'm a promise"); 94 | }).then(result => result); 95 | 96 | f2(); 97 | } 98 | 99 | Output: 100 | main 101 | f2 102 | I'm a promise 103 | f1 104 | ``` 105 | 1. main() gets invoked and prints "main". 106 | 2. SetTimeout is an browser API, f1() call back will gets added in the call queue. 107 | 3. Promise executor function will gets added into Job queue. 108 | 4. f2() will gets into execution statck and gets executed. 109 | 5. Nothing in the execution stack, Job queue gets higher precedence over call queue, Anonymous function(promise executor function) will be pushed to execution queue and gets executed. 110 | 6. Execution stack is empty and f1() will be pushed to execution stack and gets executed. 111 | 112 | Note: Job queue is always have higher precedence over Call queue. 113 | 114 | ![Asynchronous with setTimeout and Promise](asyncWithSetTimeoutAndPromise.png) -------------------------------------------------------------------------------- /ProgrammingParadigms/README.md: -------------------------------------------------------------------------------- 1 | # Programming Paradigm 2 | 3 | Programming Paradigms are different ways or styles in which the given program or programming language can be organized. 4 | 5 | Programming Paradigms are like the set of ideas and guidelines that many people have been agreed on, followed and expand upon. 6 | 7 | 1. Imperative Programming: 8 | You tell what needs to be done and how ti needs to be done. 9 | 10 | Example: 11 | ``` 12 | // Identify the numbers that are greater than 5 13 | 14 | const nums = [1,4,3,6,7,8,9,2]; 15 | const result = []; 16 | 17 | for(let i = 0; i < nums.length ; i++) { 18 | if(nums[i] > 5) { 19 | result.push(nums[i]); 20 | } 21 | } 22 | 23 | console.log(result); 24 | 25 | ``` 26 | Here we are telling the program to iterate through each element and check if it is > 5 and store it a variable result. 27 | 28 | 2. Procedural Programming: 29 | With this we wil try to split the instructions into procedures or subrotines. 30 | 31 | Example: 32 | ``` 33 | function pourIngredients() { 34 | - Pour flour in a bowl 35 | - Pour a couple eggs in the same bowl 36 | - Pour some milk in the same bowl 37 | }; 38 | 39 | function mixAndTransferToMold() { 40 | - Mix the ingredients well. 41 | - pour to mold. 42 | }; 43 | 44 | function cookandLetChill() { 45 | - cook for 35 mins 46 | - let it chill 47 | }; 48 | 49 | pourIngredients(); 50 | mixAndTransferToMold(); 51 | cookAndLetChill(); 52 | 53 | ``` 54 | 55 | 3. Functional Programming: 56 | Here we concentrate more on functions. 57 | We will group the functions logically and make sure at any given input it should produce the same output and doesnt worry anything about outside of its scope - Pure functions. 58 | 59 | Example: 60 | ``` 61 | const nums = [1,4,3,6,7,8,9,2]; 62 | 63 | function filterNums() { 64 | const result = []; 65 | for (let i = 0; i < nums.length; i++){ 66 | if(nums[i] > 5){ 67 | result.push(nums[i]); 68 | } 69 | } 70 | return result; 71 | } 72 | 73 | console.log(filterNums()); 74 | 75 | ``` 76 | 77 | 4. Declarative Programming: 78 | You tell what needs to be done in a declarative way and the program will take care of it. 79 | 80 | This will hide the complexity of how it has to be done. 81 | 82 | Example: 83 | ``` 84 | const nums = [1,4,3,6,7,8,9,2]; 85 | 86 | console.log(nums.filter((num) => num > 5)); 87 | 88 | ``` 89 | 90 | 5. OOP Programming: 91 | Here it seperates the concerns and responsibilities into entities. 92 | 93 | Example: 94 | ``` 95 | 1. Main Chef 96 | 2. Assistant chef 97 | 98 | // Main Chef 99 | class Cook () { 100 | 101 | constructor(name) { 102 | this.name = name; 103 | }; 104 | 105 | mixAndBake() { 106 | - mix the ingredients well. 107 | - Cook for 35 mins. 108 | }; 109 | 110 | } 111 | 112 | class AssistantCook () { 113 | constructor(name){ 114 | this.name = name; 115 | }; 116 | 117 | pourIngredients() { 118 | - Pour flour in a bowl 119 | - Pour a couple eggs in the same bowl 120 | - Pour some milk in the same bowl 121 | } 122 | 123 | letChill() { 124 | - let it chill. 125 | } 126 | } 127 | 128 | const mainCook = new Cook("Frank"); 129 | const assistantCook - new AssistantCook("Antony"); 130 | 131 | assistantCook.pourIngredients(); 132 | mainCook.mixAndBake(); 133 | assistantCook.letChill(); 134 | 135 | ``` -------------------------------------------------------------------------------- /PromiseChain/README.md: -------------------------------------------------------------------------------- 1 | # Promise Chain 2 | 3 | When promise chain comes into picture. 4 | 1. You want to know the out come of the Asynchronous operation. 5 | 2. You want to inter-relate two or more Asynchronous operations. When you want to pass the output of one promise as input to another promise. 6 | 3. You got 3 handlers to handle the promise. 7 | 1. .then() - To handle resolved scenario 8 | 2. .catch() - To handle rejected scenario 9 | 3. .finally() - To clean up things like db connection or remove loding icon 10 | 11 | - .then() can 12 | 1. Return another Promise. 13 | 2. Return synchronous value. 14 | 3. Return/Throw and error. 15 | 16 | - Return another Promise: 17 | ``` 18 | const getUser = new Promise((resolve, reject) => { 19 | const user = { 20 | name: "John Doe", 21 | email: "john.doe@abc.com" 22 | }; 23 | 24 | resolve(user); 25 | }); 26 | 27 | getUser 28 | .then((user) => { 29 | console.log(`Got user ${user.name}`); 30 | 31 | return new Promise((resolve, reject) => { 32 | setTimeout(() => { 33 | resolve("Bangalore); 34 | }); 35 | }) 36 | }) 37 | .then((address) => console.log(`User's address ${address}`)); 38 | 39 | ``` 40 | 41 | - Return Synchronous value: 42 | ``` 43 | const getUser = new Promise((resolve, reject) => { 44 | const user = { 45 | name: "John Doe", 46 | email: "john.doe@abc.com" 47 | }; 48 | 49 | resove(user); 50 | }); 51 | 52 | getUser 53 | .then((user) => { 54 | console.log(`Got user ${user.name}`); 55 | 56 | return user.email; 57 | }) 58 | .then((email) => { 59 | console.log(`User's email ${email}`); 60 | }); 61 | 62 | ``` 63 | 64 | - Return/Throw an error: 65 | ``` 66 | const getUser = new Promise((resolve, reject) => { 67 | const user = { 68 | name: "John Doe", 69 | email: "john.doe@abc.com", 70 | permissions: ["db", "hr", "dev"] 71 | }; 72 | 73 | resolve(user); 74 | }); 75 | 76 | getUser 77 | .then((user) => { 78 | console.log(`Got user ${user}`); 79 | 80 | if(user.permissions.includes("hr")) { 81 | throw new Error("You are not allowed."); 82 | } 83 | }) 84 | .catch((error) => { 85 | console.log(error); 86 | }); 87 | 88 | ``` 89 | 90 | Example for Promise chaining: 91 | ``` 92 | Scenario 1: 93 | 94 | const number = new Promise((resolve, reject) => { 95 | resolve(10); 96 | }); 97 | 98 | number.then((value) => { 99 | value++; 100 | return value; // Here the value is 11 101 | }); 102 | 103 | number.then((value)) => { 104 | value += 10; 105 | return value; // Here the value is 20 as we are not chaining 106 | } 107 | 108 | number.then((value) => { 109 | value += 20; 110 | return value; // Here the value is 30 as we are not chaining. 111 | }); 112 | 113 | 114 | Scenario 2: 115 | 116 | const number = new Promise((resolve, reject) => { 117 | resolve(10); 118 | }); 119 | 120 | number.then((value) => { 121 | value++; 122 | return value; // Here the value is 11 123 | }).then((value) => { 124 | value += 10; 125 | return value; // Here the value is 21 as we are chaining 126 | }).then((value) => { 127 | value += 20; 128 | return value; // Here the value is 41 as we are chaining 129 | }); 130 | 131 | ``` 132 | 133 | - .finally() - This is use to clean up stuff like db disconnect, setting off the loader icon etc... 134 | 135 | ``` 136 | const promise = new Promise((resolve, reject) => { 137 | resolve("Testing finally method."); 138 | }) 139 | 140 | // finally executor function does not take any parameter. 141 | promise.finally(() => { 142 | console.log("Running .finally()"); 143 | }).then((result) => console.log(result)); 144 | 145 | Output: 146 | Running .finally() 147 | Testing finally method. 148 | 149 | ``` 150 | Source: https://github.com/atapas/promise-interview-ready/tree/main/src/02-promise-chain -------------------------------------------------------------------------------- /PromiseAPIs/README.md: -------------------------------------------------------------------------------- 1 | # Promise APIs 2 | 1. Promise.all() 3 | 2. Promise.allSettled() 4 | 3. Promise.any() 5 | 4. Promise.race() 6 | 5. Promise.resolve() 7 | 6. Promise.reject() 8 | 9 | - Promise.all(): 10 | - It executes multiple promises and return a promise. 11 | - It will wait for all the input promises to get resolved. 12 | - If any of the input promises gets rejected, Promise.all also gets rejected immediately. 13 | - The execution time of Promise.all() is depends on the maximum time taken by an input promise. 14 | 15 | Example 16 | ``` 17 | const red = new Promise((resolve, reject) => { 18 | setTimeout(() => resolve("red), 1000); 19 | }); 20 | 21 | const green = new Promise((resolve, reject) => { 22 | setTimeout(() => resolve("green"), 3000); 23 | }); 24 | 25 | const blue = new Promise((resolve, reject) => { 26 | setTimeout(() => resolve("blue"), 5000); 27 | }); 28 | 29 | //using .then() 30 | 31 | const allPromises = Promise.all([red, green, blue]); 32 | allPromises.then((value) => console.log(value)); 33 | allPromises; 34 | 35 | //using async and await 36 | 37 | const testAll = async () => { 38 | const colors = await Promise.all([red, green, blue]); 39 | console.log(colors); 40 | }; 41 | testAll(); 42 | 43 | Output: 44 | ["red", "green", "blue"] 45 | 46 | ``` 47 | - Promise.allSettled: 48 | - The only difference between Promise.all() and Promise.allSettled(), With Promise.allSettled(), if any of the input promise gets rejected, it rejects only that promise and executes rest all other promise. 49 | - Output will contain the status and value for resolved promises and for rejected promises status and reason of rejection. 50 | 51 | Example: 52 | ``` 53 | const red = new Promise((resolve, reject) => { 54 | setTimeout(() => resolve("red"), 1000); 55 | }); 56 | 57 | const green = new Promise((resolve, reject) => { 58 | setTimeout(() => reject("Error:green"), 3000); 59 | }); 60 | 61 | const blue = new Promise((resolve, reject) => { 62 | setTimeout(() => resolve("blue"), 5000); 63 | }); 64 | 65 | const testAll = async () => { 66 | const colors = Promise.allSettled([red, green, blue]); 67 | colors.map((color) => console.log(color)); 68 | }; 69 | 70 | testAll(); 71 | 72 | Output: 73 | {status: 'fulfilled', value: 'red'} 74 | {status: 'rejected', reason: 'Error:green'} 75 | {status: 'fulfilled', value: 'blue'} 76 | 77 | ``` 78 | - Promise.any(): 79 | - It returns a promise if any one of the input promise gets resolved. 80 | - If all the input promises are gets rejected , Promise.any() will throw an AggregateError: All promises were rejected 81 | 82 | Example: 83 | ``` 84 | Scenario 1: 85 | 86 | const red = new Promise((resovle,reject) => { 87 | setTimeout(() => resolve("red"), 1000); 88 | }); 89 | 90 | const green = new Promise((resolve, reject) => { 91 | setTimeout(() => resolve("green"), 3000); 92 | }); 93 | 94 | const blue = new Promise((resolve, reject) => { 95 | setTimeout(() => resolve("blue"), 5000); 96 | }); 97 | 98 | const testAll = async () => { 99 | const colors = await Promise.any([red, green, blue]); 100 | console.log(colors) 101 | }; 102 | 103 | testAll(); 104 | 105 | Output: 106 | red - As it is one to get resolved first. 107 | 108 | Scenario 2: 109 | 110 | const red = new Promise((resovle,reject) => { 111 | setTimeout(() => reject("Error:red"), 1000); 112 | }); 113 | 114 | const green = new Promise((resolve, reject) => { 115 | setTimeout(() => resolve("green"), 3000); 116 | }); 117 | 118 | const blue = new Promise((resolve, reject) => { 119 | setTimeout(() => resolve("blue"), 5000); 120 | }); 121 | 122 | const testAll = async () => { 123 | const colors = await Promise.any([red, green, blue]); 124 | console.log(colors) 125 | }; 126 | 127 | testAll(); 128 | 129 | Output: 130 | green - As this is the next one to get resolve first. 131 | 132 | Scenario 3: 133 | 134 | const red = new Promise((resovle,reject) => { 135 | setTimeout(() => reject("Error:red"), 1000); 136 | }); 137 | 138 | const green = new Promise((resolve, reject) => { 139 | setTimeout(() => reject("green"), 3000); 140 | }); 141 | 142 | const blue = new Promise((resolve, reject) => { 143 | setTimeout(() => reject("blue"), 5000); 144 | }); 145 | 146 | const testAll = async () => { 147 | const colors = await Promise.any([red, green, blue]); 148 | console.log(colors) 149 | }; 150 | 151 | testAll(); 152 | 153 | Output: 154 | AggregateError: All promises were rejected - As all the input promises gets rejected. 155 | 156 | ``` 157 | - Promise.race(): 158 | 159 | This will execute the fastest input promise and return a promise. if it gets rsolved it will show the output. if te fastest promise gets rejected, Promise.race() will be rejected immediately. 160 | 161 | Example: 162 | ``` 163 | const red = new Promise((resolve, reject) => { 164 | setTimeout(() => resolve("red"), 1000); 165 | }); 166 | 167 | const green = new Promise((resolve, reject) => { 168 | setTimeout(() => resolve("green"), 3000); 169 | }); 170 | 171 | const blue = new Promise((resolve, reject) => { 172 | setTimeout(() => resolve("blue"), 5000); 173 | }); 174 | 175 | const testAll = async () => { 176 | const colors = await Promise.race([red, green, blue]); 177 | console.log(colors); 178 | }; 179 | 180 | testAll(); 181 | 182 | Output: 183 | red as this is the promise will take less time than any other promise. 184 | 185 | Note: if red promise gets rejected, Promise.race() will get rejected immediately. 186 | 187 | ``` 188 | 189 | - Promise.resolve(): 190 | 191 | - This will reolve only one of the input promise whichever we are going to resolve. 192 | 193 | Example: 194 | ``` 195 | const red = new Promise((resolve, reject) => { 196 | setTimeout(() => resolve("red"), 1000); 197 | }); 198 | 199 | const green = new Promise((resolve, reject) => { 200 | setTimeout(() => resolve("green"), 3000); 201 | }); 202 | 203 | const blue = new Promise((resolve, reject) => { 204 | setTimeout(() => resolve("blue"), 5000); 205 | }); 206 | 207 | const testAll = async () => { 208 | const colors = await Promise.resolve(red); 209 | console.log(colors); 210 | }; 211 | testAll(); 212 | 213 | Output: 214 | red - as we are resolving the same. 215 | 216 | ``` 217 | 218 | - Promise.reject(): 219 | 220 | - This will reject promise and preints the error stack trace. 221 | 222 | Example: 223 | ``` 224 | const red = new Promise((resolve, reject) => { 225 | setTimeout(() => resolve("red"), 1000); 226 | }); 227 | 228 | const green = new Promise((resolve, reject) => { 229 | setTimeout(() => reject("green"), 3000); 230 | }); 231 | 232 | const blue = new Promise((resolve, reject) => { 233 | setTimeout(() => resolve("blue"), 5000); 234 | }); 235 | 236 | const testAll = async () => { 237 | const colors = await Promise.reject(green); 238 | console.log(colors); 239 | }; 240 | testAll(); 241 | 242 | Output: 243 | UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "# 244 | 245 | ``` -------------------------------------------------------------------------------- /OopsConcepts/README.md: -------------------------------------------------------------------------------- 1 | # OOPS Concepts 2 | 3 | - Objects: 4 | 5 | Objects are the instance of the class. it contains Properties and Methods. 6 | 7 | if you consider "a car" as a real-life object. it has certain characterstics like color, model, horsepower etc and it can perform some actions like driving. 8 | here the characterstics of the car is called Properties and the Actions performed by an entity is called Methods. 9 | 10 | Objects can be created in two ways, 11 | - Object Literals: 12 | 13 | ``` 14 | let person = { 15 | firstName: "John", 16 | lastName: "Doe", 17 | getFullName: () => `The name of the person is ${person.firstName} ${person.lastName}` 18 | }; 19 | 20 | console.log(person.getFullName()); 21 | 22 | ``` 23 | - Object Constructor: 24 | 25 | ``` 26 | // Traditonal way 27 | 28 | function person(firstName, lastName){ 29 | this.firstName = firstName; 30 | this.lastName = lastName; 31 | }; 32 | 33 | const person1 = new person("John", "Doe"); 34 | 35 | const person2 = new person("Nagarjun", "Shroff"); 36 | 37 | console.log(`This first person name is ${person1.firstName} ${person1.lastName}`); 38 | console.log(`This second person name is ${person2.firstName} ${person2.lastName}`); 39 | 40 | ``` 41 | - Classes: 42 | 43 | Classes are the templates for creating objects. This encapsulate the data and the code which works on that data. 44 | 45 | JavaScript is a prototype-based object oriented lanaguage, which means it has no classes, rather it defines the behaviour using constructor function and then reuses it using the prototype. 46 | 47 | constructor is nothing but the special function that return an object. The special thing is when we invokedwith the "new" keyword, it assigns its prototype as the prototype of the returned object. 48 | 49 | ``` 50 | class Vehicle { 51 | constructor(name, maker, engine){ 52 | this.name = name; 53 | this.maker = maker; 54 | this.engine = engine; 55 | } 56 | 57 | getDetails(){ 58 | return `The name of the bike is ${this.maker} ${this.name}.` 59 | } 60 | } 61 | 62 | const bike1 = new Vehicle("Hayabusa", "Suzuki", "1340CC"); 63 | const bike2 = new Vehicle("Z900", "Kawasaki", "948CC"); 64 | 65 | console.log(bike1.getDetails()); 66 | console.log(bike2.getDetails()); 67 | 68 | ``` 69 | - this keyword: 70 | 71 | this keyword will always refers to the class itself and it is used to define the properties of class inside the constructor function. 72 | 73 | 74 | - 4 principles of OOP 75 | 76 | 1. Inheritance: 77 | 78 | It is concept in which certains properties and methods of one object is being used by another object. Unlike other OOP languages classes inherits classes, JavaScript object inherit objects i.e. certain properties on one object is used by another object. 79 | 80 | ``` 81 | class Person{ 82 | constructor(name){ 83 | this.name = name; 84 | }; 85 | 86 | toString(){ 87 | return `The person name is ${this.name}`; 88 | }; 89 | } 90 | 91 | class Student extends Person{ 92 | constructor(name, id){ 93 | super(name); 94 | this.id = id; 95 | }; 96 | 97 | toString(){ 98 | return `${super.toString()}, Student ID: ${this.id}`; 99 | }; 100 | } 101 | 102 | const student = new Student("Nagarjun", 123); 103 | 104 | console.log(student.toString()); 105 | 106 | Output: 107 | The person name is Nagarjun, Student ID: 123 108 | 109 | ``` 110 | 111 | 2. Encapsulation: 112 | 113 | it is a process of wrapping the properties and the method in a single unit is called Encapsulation. 114 | 115 | ``` 116 | class Person{ 117 | constructor(name, id){ 118 | this.name = name; 119 | this.id = id; 120 | }; 121 | 122 | addAddress(address){ 123 | this.address = address; 124 | }; 125 | 126 | getDetails(){ 127 | return `Name: ${this.name}, address: ${this.address}`; 128 | }; 129 | } 130 | 131 | const person = new Person("Nagarjun", 123); 132 | person.addAddress("Bangalore"); 133 | 134 | console.log(person.getDetails()); 135 | 136 | Output: 137 | Name: Nagarjun, address: Bangalore 138 | 139 | ``` 140 | 141 | 3. Abstraction: 142 | 143 | Representing the essential features, hiding the implementation details. 144 | 145 | In other OOP languages, there are access modifiers to restrict the class variables, but in JavaScript there is nothing as such. Still there are ways to do this as below 146 | 147 | ``` 148 | function Person(){ 149 | let firstName = "Nagarjun"; 150 | let lastName = "Shroff"; 151 | 152 | let noAccess = function() { 153 | return "This method can not be accessed be anyone outside this function."; 154 | }; 155 | 156 | this.access = function() { 157 | return "This method can be accessed by anyone outside of this function."; 158 | }; 159 | } 160 | 161 | const person = new Person(); 162 | console.log(person.firstName); //undefined 163 | console.log(person.noAccess); //undefined 164 | console.log(person.access()); // This method can be accessed by anyone outside of this function. 165 | 166 | ``` 167 | 4. Polymorphism: 168 | 169 | Same functions with different signatures is called many times. 170 | 171 | ``` 172 | class Shape{ 173 | 174 | area(){ 175 | return 0; 176 | } 177 | 178 | perimeter(){ 179 | return 0; 180 | } 181 | } 182 | 183 | class Circle extends Shape{ 184 | constructor(radius){ 185 | super(); 186 | this.radius = radius; 187 | } 188 | 189 | area(){ 190 | return Math.PI * this.radius ** 2; 191 | } 192 | 193 | perimeter() { 194 | return 2 * Math.PI * this.radius; 195 | } 196 | } 197 | 198 | class Rectangle extends Shape{ 199 | constructor(width, height){ 200 | super(); 201 | this.width = width; 202 | this.height = height; 203 | } 204 | 205 | area(){ 206 | return this.width * this.height; 207 | } 208 | 209 | perimeter(){ 210 | return 2 * (this.width + this.height); 211 | } 212 | } 213 | 214 | const circle = new Circle(3); 215 | const rectangle = new Rectangle(2,3); 216 | 217 | console.log(`Area of the Circle: ${circle.area()}`); 218 | console.log(`Perimeter of the Circle: ${circle.perimeter()}`); 219 | console.log(`Area of the Rectangle: ${rectangle.area()}`); 220 | console.log(`Perimeter of the rectangle: ${rectangle.perimeter()}`); 221 | 222 | ``` 223 | - Object Composition: 224 | 225 | Its an alternate to inheritence. 226 | 227 | In inheritence child classes will inherit all the properties and Methods from its parent classes. Sometime child class might not need all the properties and methods from the parent. With Object Composition, Child can get what they want from parent. 228 | 229 | ``` 230 | class Characters{ 231 | constructor(speed){ 232 | this.speed = speed; 233 | } 234 | 235 | move = () => console.log("zzzzzzziiiiiiiiiiiiinnnnnnnnnnnggggggggg"); 236 | } 237 | 238 | class Enemy extends Characters{ 239 | constructor(name, phrase, power, speed){ 240 | super(speed); 241 | this.name = name; 242 | this.phrase = phrase; 243 | this.power = power; 244 | } 245 | 246 | sayPhrase = () => console.log(this.phrase); 247 | attack = () => console.log(`I'm attacking with the power ${this.power}`) 248 | } 249 | 250 | class Alien extends Enemy{ 251 | constructor(name, phrase, power, speed){ 252 | super(name, phrase, power, speed); 253 | this.species = "alien"; 254 | } 255 | 256 | fly = () => comsole.log(`I can fly with the speed ${this.speed}`); 257 | } 258 | 259 | class Bug extends Enemy{ 260 | constructor(name, phrase, power, speed){ 261 | super(name, phrase, power, speed); 262 | this.species = "bug"; 263 | } 264 | 265 | hide = () => console.log("You cant catch me now!"); 266 | } 267 | 268 | class Robot extends Enemy{ 269 | constructor(name, phrase, power, speed){ 270 | super(name, phrase, power, speed); 271 | this.species = "robot"; 272 | } 273 | 274 | transform = () => console.log("Optimus Prime!"); 275 | } 276 | 277 | const alien = new Alien("Ali", "I'm Ali alien", 10, 20); 278 | const bug = new Bug("Buggy", "Your debugger doesnt work with me!", 20, 50); 279 | const robot = new Robot("Chitti", "Vasi meh meh", 50, 120); 280 | 281 | const enablingFlyTobug = (obj) => { 282 | obj.fly = () => console.log(`Now ${obj.name} can also fly!!!`); 283 | }; 284 | 285 | enablingFlyTobug(bug); 286 | bug.fly(); 287 | 288 | Output: 289 | Now Buggy can also fly!!! 290 | 291 | ``` --------------------------------------------------------------------------------