├── Backend Syllabus.pdf ├── BasicHttpServerUsingNode ├── .gitignore ├── httpIndex.js ├── index.js ├── package-lock.json └── package.json ├── Computer_Network_Notes.pdf ├── DBMS ├── Introduction To Databases and DBMS │ ├── Black Paper (1).pdf │ ├── DBMS.pdf │ └── notes db.pdf ├── Road To Normalisation │ ├── Black Paper Landscape (11) 2.pdf │ ├── Intro To Normalisation.pdf │ └── Normalization-I.md ├── SQL1 │ ├── SQL1.md │ └── SQL1.pdf ├── SQL2 │ ├── SQL2.md │ ├── SQL2.pdf │ └── notes.md ├── SQL3 │ ├── SQL3.md │ └── SQL3_JOIN.pdf ├── sNormalisation Part 2 │ ├── Black Paper Landscape (12) 2.pdf │ ├── Normalization Part_2.pdf │ └── Normalization-II.md └── sNormalisation Part 3 │ ├── Black Paper Landscape (13).pdf │ ├── hw.md │ └── requirements.md ├── JavaScript ├── Chapter 01 - Operators │ ├── Code │ │ ├── AdditionalOperators.js │ │ └── ToPrimitives.js │ └── Theory │ │ └── Operators-Conditionals-Loops-basic.md ├── Chapter 02 - Introduction To Coersion │ ├── Code │ │ ├── AbstractEquality.js │ │ ├── CoersionExamples.js │ │ ├── CornerCasesCoersion.js │ │ ├── ExplicitConversion.js │ │ ├── NaN.js │ │ ├── NegativeZeroes.js │ │ ├── StrictEquality.js │ │ └── ToBooleanDemo.js │ ├── Coersion,_NaN,_Equality_Operators.pdf │ └── Theory │ │ └── Coersion.md ├── Chapter 03 - Scopes and Function Expression │ ├── Code │ │ ├── blockscope.js │ │ ├── constdemo.js │ │ ├── demo.js │ │ ├── function_in_blocks.js │ │ ├── function_in_blocks_strict_mode.js │ │ ├── functionexpression.js │ │ ├── functionexpressiondemo.js │ │ ├── functionscope.js │ │ ├── globalscope.js │ │ ├── let_block_scoping.js │ │ ├── nestedscopes.js │ │ ├── scopes1.js │ │ ├── scopes2.js │ │ ├── scopes3.js │ │ ├── scopesfunctionexpression.js │ │ ├── strict_mode_auto_global.js │ │ ├── usecaseofnamedfunctionexpression.js │ │ ├── usecasevar.js │ │ ├── useccaselet.js │ │ ├── var_in_block.js │ │ └── whichscoping.js │ └── Theory │ │ ├── Function-Expression.md │ │ ├── Is-Javascript-Compiled_-Lexical-Scoping.md │ │ └── Lexical-Scoping-Auto-Global.md ├── Chapter 04 - Introduction To Callbacks │ ├── Code │ │ ├── callbackdemo2.js │ │ ├── callbacks.js │ │ ├── callbacksdemo.js │ │ ├── hof.js │ │ └── problemswithcallbacks.js │ ├── Theory │ │ └── Callbacks-IVC.md │ └── callbacks_Inversion_of_control_.pdf ├── Chapter 05 - Async nature │ ├── Code │ │ ├── async.js │ │ ├── demo.js │ │ └── sync.js │ ├── How_runtime_helps_in_async_nature_of_JS.pdf │ └── Theory │ │ ├── Async-Behaviour-with-Callbacks.md │ │ └── How-runtime-helps-in-async-nature-of-JS.md ├── Chapter 06 - Introduction To Promises │ ├── Code │ │ ├── createPromiseWithLoop.js │ │ ├── createPromiseWithSetTimeout.js │ │ ├── passingMultipleValues.js │ │ └── returningBeforeResolveOrReject.js │ ├── Introduction_to_promises.pdf │ └── Theory │ │ └── intro-to-promises.md ├── Chapter 07 - How to consume a promise- Part-2 │ ├── Code │ │ ├── consumingPromise.js │ │ ├── microtask_demo.js │ │ └── microtaskqueuedemo.js │ ├── How to consume a promise.pdf │ └── notes.pdf ├── Chapter 08 - Part - 3 Promises practice │ ├── Code │ │ ├── demo1.js │ │ ├── demo2.js │ │ ├── demo3.js │ │ ├── pain.js │ │ ├── promisechainingmdn.js │ │ ├── promisedownloaddummy.js │ │ └── promiseschaineddemo.js │ ├── Part 3 - Promises Practice.pdf │ └── Theory │ │ └── notes.pdf ├── Chapter 09 - Part - 4 Promises and callbacks practice │ ├── Code │ │ ├── callbackImpl.js │ │ └── promiseimpl.js │ └── Promises-practise-question.png ├── Chapter 10 - Closures - Iterators and Generators │ ├── Closures_Iterators_And_Generators.pdf │ └── Code │ │ ├── closures_Demo.js │ │ ├── generator_demo.js │ │ ├── intro_to_closures.js │ │ └── iterators_self_demo.js ├── Chapter 11 - Async-Await - Try and Catch │ ├── Async-Await.pdf │ └── Code │ │ ├── async_await_Demo.js │ │ ├── catchpromise.js │ │ ├── demo.js │ │ ├── errorasyncawait.js │ │ ├── errorpromise.js │ │ ├── generator_adv_demo.js │ │ ├── promiseall.js │ │ └── promises_generator.js ├── Chapter 12 - class, object, this keyword │ ├── Code │ │ ├── class.js │ │ ├── this.demo3.js │ │ ├── this_demo.js │ │ └── this_demo2.js │ └── class, this.pdf ├── Chapter 13 - new keyword, constructor function, private variables │ ├── Code │ │ ├── functionConstructor.js │ │ └── new_keyword_demo.js │ └── new, constructor in JS.pdf └── Chapter 14 - Prototype based inheritance │ └── Prototyple Chaining .pdf ├── Namastey_JS.pdf ├── NodeJS ├── Chapter 01 - Intro To Node Js │ ├── Intro to NodeJs.pdf │ ├── diff_node_browser.js │ └── globals_node.js └── Chapter 02 - Modules in Nodejs │ └── Module in Nodejs.pdf ├── READMe.md └── test.js /Backend Syllabus.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/Backend Syllabus.pdf -------------------------------------------------------------------------------- /BasicHttpServerUsingNode/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules -------------------------------------------------------------------------------- /BasicHttpServerUsingNode/httpIndex.js: -------------------------------------------------------------------------------- 1 | const http = require("http"); // require the http module 2 | 3 | const PORT = 800; 4 | 5 | // using the createServer function we can actually create a basic http sever using http module. 6 | // This function returns a server object, and takes a callback as an argument. 7 | // this function created a server object but didn't start the sever. 8 | const server = http.createServer(function listener(request, response) { 9 | /** 10 | * request -> we wil able to details ofincoming http request -> object 11 | * response -> we wiill able to configure what response we need to 12 | * send to an incoming http request -> object 13 | * 14 | */ 15 | // this callback is a kind of listener that is going to collect 16 | // every http request that we will make to our server 17 | 18 | if (request.url === "/home") { 19 | // if we make a request on /home this if block will be executed 20 | console.log(request.method); 21 | // if we want to send data in multiple chunks 22 | response.write("first response"); 23 | response.write("second response"); 24 | 25 | response.end("Welcome to home!"); 26 | } 27 | 28 | // console.log("incoming request details: ", request.url); 29 | // console.log("response object details: ", response); 30 | console.log("Request received"); 31 | }); 32 | 33 | server.listen(PORT, function exec() { 34 | // once we successfully boot up the server on the given port, this callback will be executed. 35 | console.log(`Server is Up and running on PORT: ${PORT}`); 36 | }); 37 | -------------------------------------------------------------------------------- /BasicHttpServerUsingNode/index.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | 3 | const app = express(); // create a express server object 4 | 5 | const PORT = 10; 6 | 7 | 8 | const myLogger = (req, res, next) => { 9 | console.log("loggging from middleware 1") 10 | return res.json({msg: "returning"}); 11 | next(); // calls the next middleware 12 | } 13 | 14 | const extraLogger = (req, res, next) => { 15 | console.log("loggging from middleware 2") 16 | next(); 17 | } 18 | 19 | const middleware = [myLogger, extraLogger] // created the array for reusibility.. 20 | 21 | app.get("/home",middleware, (req, res) => { 22 | console.log("Last middleware") 23 | res.json({ 24 | message: "Ok get" 25 | }) 26 | }); 27 | 28 | app.listen(PORT, () => { 29 | console.log(`Example app listening on port ${PORT}`); 30 | }); 31 | -------------------------------------------------------------------------------- /BasicHttpServerUsingNode/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "basichttpserverusingnode", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "express": "^4.18.2" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Computer_Network_Notes.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/Computer_Network_Notes.pdf -------------------------------------------------------------------------------- /DBMS/Introduction To Databases and DBMS/Black Paper (1).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/DBMS/Introduction To Databases and DBMS/Black Paper (1).pdf -------------------------------------------------------------------------------- /DBMS/Introduction To Databases and DBMS/DBMS.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/DBMS/Introduction To Databases and DBMS/DBMS.pdf -------------------------------------------------------------------------------- /DBMS/Introduction To Databases and DBMS/notes db.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/DBMS/Introduction To Databases and DBMS/notes db.pdf -------------------------------------------------------------------------------- /DBMS/Road To Normalisation/Black Paper Landscape (11) 2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/DBMS/Road To Normalisation/Black Paper Landscape (11) 2.pdf -------------------------------------------------------------------------------- /DBMS/Road To Normalisation/Intro To Normalisation.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/DBMS/Road To Normalisation/Intro To Normalisation.pdf -------------------------------------------------------------------------------- /DBMS/Road To Normalisation/Normalization-I.md: -------------------------------------------------------------------------------- 1 | 2 | **What is Databases Schema** → blue print 3 | - It is the blue print of actual db, that we will create. 4 | - How we will store data, structures of table etc is defined in it. 5 | 6 | **Databases Instance?** 7 | - A database instance is a set of memory structures and background processes that manage database files. It includes multiple parts, including the relational database management system (RDBMS) software, table structure, stored procedures, and other functionality 8 | 9 | **Functional Dependency.** 10 | - It’s like a relationship between two things where one thing can help you figure out the other thing. 11 | - It defined relationship between two attributes. 12 | - **X**(determined) → **Y**(dependent) (**Y** is functionally dependent on **X**) 13 | - **Y** depends on **X**, means that for evert valid value of **X**, we can uniquely identify **Y**. 14 | 15 | **How can you identify functional dependency ?** 16 | - To identify functional dependencies, you need to examine the data and the business rules of the database. You can check if a functional dependency exists by asking yourself if the value of one attribute changes, does the value of another attribute change as well? Can the value of another attribute be determined if the value of one attribute is known? 17 | 18 | **Assertion** 19 | - Assertions have been part of the SQL standard since SQL-92. They can be used to implement what’s commonly called cross-row constraints or multi-table check constraints. 20 | - In the SQL standard, both assertions and check constraints are considered “constraints” which are rules that the data actually contained in the database must comply with. 21 | 22 | For example, let’s say you’re writing a program that calculates the square root of a number. You might include an assertion that checks that the number you’re trying to find the square root of is not negative because you know that the square root of a negative number is not a real number. 23 | 24 | example of how an assertion might be used in SQL: 25 | 26 | Let's say you have two tables: `Orders` and `Customers`. The `Orders` table has a column for the customer ID and the `Customers` table has a column for the customer's credit limit. You want to make sure that no customer can place an order that exceeds their credit limit. 27 | 28 | You could create an assertion that checks that the total value of all orders for each customer is less than or equal to their credit limit. The assertion would look something like this: 29 | 30 | ```sql 31 | CREATE ASSERTION orders_within_credit_limit 32 | CHECK ( 33 | NOT EXISTS ( 34 | SELECT 1 35 | FROM Customers c 36 | JOIN Orders o ON c.customer_id = o.customer_id 37 | GROUP BY c.customer_id, c.credit_limit 38 | HAVING SUM(o.order_value) > c.credit_limit 39 | ) 40 | ); 41 | ``` 42 | 43 | This assertion checks that there are no customers for whom the total value of their orders is greater than their credit limit. If this condition is ever violated, the assertion will fail and an error will be raised. 44 | 45 | ### Axioms in DBMS 46 | 47 | Axioms are a set of rules that define how the attributes in a relational database are functionally dependent on each other. In DBMS, there are three axioms: reflexivity, augmentation, and transitivity. 48 | 49 | #### Reflexivity 50 | 51 | The first axiom, reflexivity, states that if one attribute is a subset of another attribute, then the subset attribute is functionally dependent on the other attribute. For example, consider the attributes of an address: address, state, and house number. If the state is a subset of the address, then the state is functionally dependent on the address. This means that if you know the address, you can determine the state. 52 | 53 | #### Augmentation 54 | 55 | The second axiom, augmentation, states that if **X → Y**, then **X2 → Y2** for any attribute **Z**. This axiom leads to partial dependency. This means that if a non-key attribute is functionally dependent on a part of the primary key, then it is functionally dependent on the whole primary key. For example, suppose you have a table with the attributes of a person's name, address, and phone number. If the name is the primary key, and the phone number is functionally dependent on the address, then the phone number is partially dependent on the primary key. 56 | 57 | #### Transitivity 58 | 59 | The third axiom, transitivity, states that if **X → Y** and **Y → Z**, then **X → Z**. This axiom defines that if there is a functional dependency between X and Y, and there is a functional dependency between Y and Z, then there must be a functional dependency between X and Z. For example, suppose you have a table with the attributes of a person's name, address, and phone number. If the name is functionally dependent on the address, and the address is functionally dependent on the phone number, then the name is functionally dependent on the phone number. 60 | 61 | ### Database Keys 62 | 63 | In a database, a key is a set of one or more columns that uniquely identifies a row in a table. There are several types of keys in a database, including primary keys, candidate keys, and foreign keys. 64 | 65 | #### super key 66 | 67 | A **super key** is a set of one or more columns that can be used to uniquely identify a row in a table. In other words, it’s a set of columns that contains a candidate key. A super key can have additional columns that are not necessary for unique identification. 68 | 69 | For example, let’s say you have a table called `Employees` with columns for `employee_id`, `first_name`, `last_name`, and `email`. The `employee_id` column is the primary key and is also a candidate key. The set of columns `{employee_id, first_name}` is a super key because it contains the candidate key `employee_id` and can be used to uniquely identify each row. However, the `first_name` column is not necessary for unique identification because the `employee_id` column alone is sufficient. 70 | 71 | #### candidate key 72 | 73 | A **candidate key** is a minimal super key, meaning it’s a set of columns that can uniquely identify each row in a table and no subset of the columns can also uniquely identify each row. In other words, it’s a super key with no unnecessary columns. 74 | 75 | For example, let’s say you have a table called `Customers` with columns for `customer_id`, `first_name`, `last_name`, and `email`. The `customer_id` column is the primary key and is also a candidate key because it can uniquely identify each row. The set of columns `{customer_id, first_name}` is a super key but not a candidate key because the `first_name` column is not necessary for unique identification. 76 | 77 | A table can have multiple candidate keys. In our `Customers` example, if each customer also had a unique email address, the `email` column could be another candidate key. 78 | 79 | #### composite key 80 | 81 | A **composite key** is a key that consists of two or more columns. It’s used when a single column is not sufficient to uniquely identify each row in a table. 82 | 83 | For example, let’s say you have a table called `Enrollments` with columns for `student_id`, `course_id`, and `enrollment_date`. In this case, neither the `student_id` nor the `course_id` column alone can uniquely identify each row because a student can enroll in multiple courses and a course can have multiple students. However, the combination of `student_id` and `course_id` can uniquely identify each row because each student can only enroll in a specific course once. So, the set of columns `{student_id, course_id}` is a composite key. 84 | 85 | #### primary key 86 | 87 | A **primary key** is a column or set of columns that uniquely identifies each row in a table. It’s a special type of candidate key that is chosen by the database designer to be the main way of identifying rows in the table. 88 | 89 | For example, let’s say you have a table called `Students` with columns for `student_id`, `first_name`, and `last_name`. The `student_id` column could be the primary key because each student has a unique ID. This means that you can use the `student_id` column to look up a specific student in the table. 90 | 91 | A primary key must be unique and cannot contain null values. It’s also usually indexed to improve the performance of queries that use it. 92 | 93 | #### alternate key 94 | 95 | An **alternate key** is a candidate key that is not the primary key. In other words, it’s a column or set of columns that can uniquely identify each row in a table but is not chosen as the primary key. 96 | 97 | For example, let’s say you have a table called `Customers` with columns for `customer_id`, `first_name`, `last_name`, and `email`. The `customer_id` column is the primary key and is also a candidate key. If each customer also had a unique email address, the `email` column could be an alternate key because it can uniquely identify each row but is not the primary key. 98 | 99 | Alternate keys are sometimes called secondary keys or non-prime keys. 100 | 101 | #### foreign key 102 | 103 | A **foreign key** is a column or set of columns in one table that refers to the primary key of another table. It’s used to create a relationship between the two tables and to enforce referential integrity. 104 | 105 | For example, let’s say you have two tables: `Orders` and `Customers`. The `Orders` table has columns for `order_id`, `customer_id`, and `order_date`. The `Customers` table has columns for `customer_id`, `first_name`, and `last_name`. The `customer_id` column in the `Customers` table is the primary key. 106 | 107 | In this case, the `customer_id` column in the `Orders` table could be a foreign key that refers to the `customer_id` primary key in the `Customers` table. This creates a relationship between the two tables where each order is associated with a specific customer. The database will enforce referential integrity by ensuring that any value entered into the `customer_id` column in the `Orders` table must match a value in the `customer_id` column in the `Customers` table. 108 | 109 | #### Functional dependency Closure 110 | 111 | In a database, the **closure** of a set of functional dependencies is the set of all functional dependencies that can be derived from the original set. In other words, it’s the set of all functional dependencies that must hold in any relation that satisfies the original set of functional dependencies. 112 | 113 | Let me explain it with an example. Let’s say you have a relation with columns for `student_id`, `first_name`, `last_name`, and `email`. You know that each student has a unique ID and a unique email address. So, you have two functional dependencies: `student_id -> first_name` and `student_id -> last_name`. 114 | 115 | The closure of this set of functional dependencies would include the original two functional dependencies as well as any other functional dependencies that can be derived from them. In this case, the closure would also include the functional dependency `student_id -> email` because if you know a student’s ID, you can also determine their email address. 116 | 117 | #### Attribute Closure 118 | 119 | The **attribute closure** of a set of attributes is the set of all attributes that are functionally dependent on the original set. In other words, it’s the set of all attributes that can be determined if you know the values of the original set of attributes. 120 | 121 | Let me explain it with an example. Let’s say you have a relation with columns for `student_id`, `first_name`, `last_name`, and `email`. You know that each student has a unique ID and a unique email address. So, you have two functional dependencies: `student_id -> first_name` and `student_id -> last_name`. 122 | 123 | The attribute closure of the set of attributes `{student_id}` would include the original attribute `student_id` as well as any other attributes that can be determined if you know the value of `student_id`. In this case, the attribute closure would also include the attributes `first_name` and `last_name` because if you know a student’s ID, you can also determine their first name and last name. 124 | 125 | ### N+1 problem 126 | 127 | The **N+1 problem** is a performance issue that can happen when you’re working with databases. It happens when your code makes too many queries to the database, slowing down your program. 128 | 129 | Let me explain it with an example. Let’s say you have a database with two tables: `Authors` and `Books`. The `Authors` table has columns for `author_id` and `name`. The `Books` table has columns for `book_id`, `title`, and `author_id`. 130 | 131 | Now, imagine you want to write a program that displays a list of all authors and their books. You might write code that first queries the `Authors` table to get a list of all authors. Then, for each author, you make another query to the `Books` table to get a list of all their books. 132 | 133 | This is where the N+1 problem comes in. If you have N authors, your code will make N+1 queries to the database: one query to get the list of authors and N queries to get the books for each author. This can be very slow if you have a lot of authors. 134 | 135 | The solution to the N+1 problem is to use a technique called **eager loading**. Instead of making multiple queries to the database, you make one query that gets all the data you need at once. In our example, you could use a JOIN statement to get a list of all authors and their books with just one query. 136 | -------------------------------------------------------------------------------- /DBMS/SQL1/SQL1.md: -------------------------------------------------------------------------------- 1 | 2 | ## Lecture Notes: Introduction to SQL 3 | 4 | SQL stands for Structured Query Language, and it is a language used to manage and manipulate relational databases. In this lecture, we will cover the basic SQL commands needed to create and manage databases and tables. We will also learn how to insert data into tables and retrieve data using SELECT statements. 5 | 6 | ### SQL Commands: 7 | 8 | - This command is used to display all the available databases on the system. 9 | 10 | ```sql 11 | SHOW DATABASES; 12 | ``` 13 | 14 | - This command is used to select a specific database to run queries on. 15 | 16 | ```sql 17 | USE database_name; 18 | ``` 19 | 20 | - This command is used to list all the tables within the selected database. 21 | 22 | ```sql 23 | SHOW TABLES; 24 | ``` 25 | 26 | - This command is used to create a new database. 27 | 28 | ```sql 29 | CREATE DATABASE database_name; 30 | ``` 31 | 32 | - This command is used to create a new table within the selected database. 33 | 34 | ```sql 35 | CREATE TABLE table_name ( 36 | column_name1 datatype, 37 | column_name2 datatype, 38 | ... 39 | ); 40 | ``` 41 | 42 | - This command is used to show the structure and description of the specified table. 43 | 44 | ```sql 45 | DESC table_name; 46 | ``` 47 | 48 | - This command is used to insert values into a specified table. 49 | 50 | ```sql 51 | INSERT INTO table_name (col1, col2, ...) VALUES (value1, value2, ...); 52 | ``` 53 | 54 | - This command is used to retrieve specific column data from a specified table. Use * in place of column name to retrieve all the columns. 55 | 56 | ```sql 57 | SELECT column_name FROM table_name; 58 | ``` 59 | 60 | - This command is used to retrieve data from a specified table based on specified conditions. 61 | 62 | ```sql 63 | SELECT * FROM table_name WHERE conditions; 64 | ``` 65 | 66 | Examples: 67 | 68 | ```sql 69 | SELECT * FROM second WHERE DoB > '2000-01-01' AND Gender = 'Female'; 70 | SELECT * FROM second ORDER BY DoB DESC; 71 | SELECT * FROM second WHERE NOT Gender = 'Male’; 72 | SELECT * FROM second WHERE DoB > '2020-01-03' OR Gender = 'Female'; 73 | SELECT * FROM second WHERE Name LIKE "_a%"; 74 | SELECT * FROM second WHERE Name LIKE "%a%"; 75 | SELECT * FROM second WHERE Gender = 'Female' ORDER BY DoB DESC LIMIT 2; 76 | ``` 77 | 78 | ### SQL Tables: 79 | 80 | In order to create tables, we use the CREATE TABLE command, followed by the table name, and then a list of column names and their data types. Each column can have a unique data type, such as varchar or integer. We can also specify other properties for columns, such as NOT NULL or UNIQUE. 81 | 82 | Once we have created a table, we can insert data into it using the INSERT INTO command. We specify the table name, followed by the column names we want to insert data into, and then the values for those columns. 83 | 84 | Finally, we can retrieve data from tables using SELECT statements. We can specify conditions using operators such as AND, OR, and NOT, as well as comparison operators such as >, <, and =. We can also sort data using the ORDER BY command, and limit the amount of data returned using the LIMIT command. -------------------------------------------------------------------------------- /DBMS/SQL1/SQL1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/DBMS/SQL1/SQL1.pdf -------------------------------------------------------------------------------- /DBMS/SQL2/SQL2.md: -------------------------------------------------------------------------------- 1 | # Topic: SQL Table Operations 2 | 3 | ## Introduction: 4 | 5 | - SQL (Structured Query Language) is a programming language used for managing relational databases. 6 | - It provides various commands to perform operations on the database tables such as create, update, insert, delete, and select. 7 | 8 | ## I. Basic Commands: 9 | 10 | A. Show Database - to show all the databases available on your system. 11 | 12 | ```sql 13 | SHOW DATABASES; 14 | ``` 15 | 16 | B. Select Database - to select a particular database to run queries on. 17 | 18 | ```sql 19 | USE [database_name]; 20 | ``` 21 | 22 | C. Show Tables - to list down all the tables of a particular selected database. 23 | 24 | ```sql 25 | SHOW TABLES; 26 | ``` 27 | 28 | D. Create Database - to create a new database. 29 | 30 | ```sql 31 | CREATE DATABASE [database_name]; 32 | ``` 33 | 34 | E. Create Table - to create a new table. 35 | ```sql 36 | CREATE TABLE [table_name] ( 37 | [column_name_1] [datatype_1], 38 | [column_name_2] [datatype_2], 39 | ... 40 | ); 41 | ``` 42 | 43 | F. Describe Table - to show the structure and description of the table. 44 | ```sql 45 | DESC [table_name]; 46 | ``` 47 | 48 | 49 | G. Insert Values - to insert values into a table. 50 | ```sql 51 | INSERT INTO [table_name] ([column_name_1], [column_name_2], ...) 52 | VALUES ([value_1], [value_2], ...); 53 | ``` 54 | 55 | H. Select Data 56 | 57 | ```sql 58 | --- to get specific column data from a table. 59 | SELECT [column_name] FROM [table_name]; 60 | 61 | -- to get all the columns. 62 | SELECT * FROM [table_name]; 63 | 64 | -- to get filtered data based on the given conditions. 65 | SELECT [column_name] FROM [table_name] WHERE [conditions]; 66 | ``` 67 | 68 | ## II. Advanced Commands: 69 | 70 | A. Delete Rows - to delete rows from a table based on certain conditions. 71 | 72 | ```sql 73 | DELETE FROM [table_name] WHERE [conditions] ORDER BY [column_name] LIMIT [number]; 74 | ``` 75 | 76 | 77 | B. Update Rows - to update rows in a table based on certain conditions. 78 | ```sql 79 | UPDATE [table_name] SET [column_name_1] = [value_1] WHERE [conditions]; 80 | ``` 81 | 82 | 83 | C. Alter Table 84 | ```sql 85 | -- to modify an existing column. 86 | ALTER TABLE [table_name] CHANGE [old_column_name] [new_column_name] [datatype/constraint]; 87 | 88 | -- to add a new column to the table. 89 | ALTER TABLE [table_name] ADD [column_name] [datatype/constraint]; 90 | ``` 91 | 92 | D. Aggregate Functions - to perform calculations on columns. 93 | ```sql 94 | SELECT function_name FROM [table_name]; 95 | ``` 96 | 97 | Functions include SUM, AVG, COUNT, and DISTINCT. 98 | 99 | E. Group By - to group data based on a particular column. 100 | 101 | ```sql 102 | SELECT [column_name], COUNT(*) FROM [table_name] GROUP BY [column_name]; 103 | ``` 104 | 105 | F. Order By - to sort data in ascending or descending order. 106 | ```sql 107 | SELECT [column_name] FROM [table_name] ORDER BY [column_name] [ASC/DESC]; 108 | ``` 109 | 110 | G. Limit - to limit the number of rows returned by the query. 111 | ```sql 112 | SELECT [column_name] FROM [table_name] LIMIT [number]; 113 | ``` 114 | 115 | H. Concatenate Strings - to combine two or more strings into a single column. 116 | ```sql 117 | SELECT CONCAT([column_name_1], ' ', [column_name_2]) AS [new_column_name] FROM [table_name]; 118 | ``` 119 | 120 | **Conclusion:** 121 | 122 | SQL provides various commands to perform operations on tables in a database. 123 | The basic commands include show database, select database, show tables, create database, create table, describe table, insert values, and select data. 124 | The advanced commands include delete rows, update rows, alter table, aggregate functions, group by, order by, limit, and concatenate strings. -------------------------------------------------------------------------------- /DBMS/SQL2/SQL2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/DBMS/SQL2/SQL2.pdf -------------------------------------------------------------------------------- /DBMS/SQL2/notes.md: -------------------------------------------------------------------------------- 1 | # DELETE 2 | In MySQL, the DELETE command is used to delete one or more records from a table. The basic syntax for the DELETE command is as follows: 3 | 4 | DELETE FROM table_name WHERE condition; 5 | 6 | Here, table_name is the name of the table from which you want to delete records, and condition specifies the criteria for selecting the records to be deleted. If you omit the WHERE clause, all records in the table will be deleted. 7 | 8 | For example, to delete all records from a table named mytable, you would use the following command: 9 | 10 | DELETE FROM mytable; 11 | To delete only specific records based on a condition, you would use a command like this: 12 | 13 | 14 | DELETE FROM mytable WHERE id = 1; 15 | This would delete only the record(s) where the id column has a value of 1. 16 | 17 | 18 | # UPDATE 19 | In MySQL, the UPDATE command is used to modify existing records in a table. The basic syntax for the UPDATE command is as follows: 20 | 21 | UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition; 22 | Here, table_name is the name of the table you want to modify, column1, column2, etc. are the names of the columns you want to update, and value1, value2, etc. are the new values you want to set for those columns. The WHERE clause specifies the criteria for selecting the records to be updated. 23 | 24 | For example, to change the name and age columns of a record where id equals 1 in a table named mytable, you would use the following command: 25 | 26 | UPDATE mytable SET name = 'John', age = 30 WHERE id = 1; 27 | This would update the name column to "John" and the age column to 30 for the record(s) where the id column has a value of 1. 28 | 29 | It is important to use a WHERE clause when using the UPDATE command, otherwise all records in the table will be updated. 30 | 31 | 32 | # ALTER 33 | In MySQL, the ALTER command is used to modify the structure of a table, such as adding or removing columns, changing column data types, or renaming the table itself. The basic syntax for the ALTER command is as follows: 34 | 35 | ALTER TABLE table_name action; 36 | Here, table_name is the name of the table you want to modify, and action specifies the modification you want to make. 37 | 38 | Some examples of ALTER commands include: 39 | 40 | - Adding a new column to a table: 41 | 42 | ALTER TABLE mytable ADD COLUMN new_column_name data_type; 43 | This would add a new column with the specified name and data type to the table named mytable. 44 | 45 | - Changing the data type of an existing column: 46 | 47 | ALTER TABLE mytable MODIFY COLUMN column_name new_data_type; 48 | This would change the data type of the specified column in the table named mytable. 49 | 50 | - Renaming a table: 51 | 52 | ALTER TABLE old_table_name RENAME TO new_table_name; 53 | This would rename the table named old_table_name to new_table_name. 54 | 55 | Note that when using the ALTER command to modify a table, there is a possibility that data loss or corruption can occur. Therefore, it is important to backup your data before making any significant changes to a table's structure. 56 | 57 | 58 | # Difference between ALTER and UPDATE command 59 | The main difference between ALTER and UPDATE commands in MySQL is that ALTER is used to modify the structure of a table, while UPDATE is used to modify the data within a table. 60 | 61 | The ALTER command can be used to add or remove columns, change column data types, add or remove indexes, and rename a table. The ALTER command modifies the structure of the table and affects the way data is stored and retrieved from the table. 62 | 63 | On the other hand, the UPDATE command is used to modify the values of existing records within a table. It changes the data stored in the table and does not affect the structure of the table. 64 | 65 | In summary, ALTER is used to modify the structure of a table, while UPDATE is used to modify the data stored within the table. 66 | 67 | 68 | # ADD AFTER and ADD FIRST 69 | In MySQL, when adding a new column to an existing table using the ALTER command, you can specify the position of the new column within the table using the "ADD COLUMN" statement with the "AFTER" or "FIRST" keyword. 70 | 71 | ADD COLUMN ... AFTER: When using the "AFTER" keyword, you can specify the name of an existing column after which the new column will be added. For example: 72 | 73 | ALTER TABLE mytable ADD COLUMN new_column_name data_type AFTER existing_column_name; 74 | This will add a new column with the specified name and data type after the existing column with the specified name. 75 | 76 | ADD COLUMN ... FIRST: When using the "FIRST" keyword, the new column will be added as the first column in the table. For example: 77 | 78 | ALTER TABLE mytable ADD COLUMN new_column_name data_type FIRST; 79 | This will add a new column with the specified name and data type as the first column in the table. 80 | 81 | Note that the "AFTER" and "FIRST" keywords are optional when using the "ADD COLUMN" statement in the ALTER command. If you do not specify either keyword, the new column will be added as the last column in the table. 82 | 83 | 84 | # DROP 85 | In MySQL, the DROP command is used to delete a database, a table, or an index. The basic syntax for the DROP command is as follows: 86 | 87 | - To drop a database: 88 | DROP DATABASE database_name; 89 | 90 | - To drop a table: 91 | DROP TABLE table_name; 92 | 93 | - To drop an index: 94 | DROP INDEX index_name ON table_name; 95 | 96 | Here, database_name is the name of the database you want to delete, table_name is the name of the table you want to delete, and index_name is the name of the index you want to delete. 97 | 98 | It is important to note that the DROP command permanently deletes the database, table, or index, along with all data it contains. Therefore, it is important to use the DROP command with caution and make sure you have a backup of any data you want to preserve. 99 | 100 | 101 | # DROP command with ALTER command 102 | The DROP command and the ALTER command are both used for modifying the structure of a table, but they have different purposes. The DROP command is used to delete an existing table, database or index, while the ALTER command is used to modify the structure of a table. 103 | 104 | It is possible to use the DROP command within an ALTER command to delete a column from a table. The syntax for using the DROP command with ALTER is as follows: 105 | 106 | ALTER TABLE table_name DROP COLUMN column_name; 107 | Here, table_name is the name of the table from which you want to delete a column, and column_name is the name of the column you want to delete. 108 | 109 | This ALTER command will remove the specified column from the table permanently, along with all data stored in that column. Therefore, it is important to make sure you have a backup of any data you want to preserve before using the DROP command within an ALTER command. 110 | 111 | 112 | # DISTINCT 113 | In MySQL, the DISTINCT keyword is used in a SELECT statement to eliminate duplicate rows from the result set. It is used in conjunction with the SELECT keyword to retrieve unique values from one or more columns of a table. 114 | 115 | The basic syntax for using the DISTINCT keyword in MySQL is as follows: 116 | 117 | SELECT DISTINCT column1, column2, ... FROM table_name; 118 | 119 | Here, column1, column2, etc. are the columns from which you want to retrieve distinct values, and table_name is the name of the table containing those columns. 120 | 121 | For example, if you have a table named "customers" with columns 122 | "customer_id", "first_name", and "last_name", and you want to retrieve the unique values from the "last_name" column, you would use the following query: 123 | 124 | SELECT DISTINCT last_name FROM customers; 125 | 126 | This query would return a list of unique last names from the "customers" table, with no duplicates. 127 | 128 | Note that the DISTINCT keyword only applies to the columns listed in the SELECT statement. If you specify multiple columns, the result set will contain unique combinations of values from those columns, but not necessarily unique values for each individual column. 129 | 130 | 131 | # COUNT 132 | In MySQL, the COUNT function is used to count the number of rows that match a specified condition in a table. It can be used with the SELECT statement to retrieve the number of rows in a table or the number of rows that match a specific condition. 133 | 134 | The basic syntax for using the COUNT function is as follows: 135 | 136 | SELECT COUNT(*) FROM table_name; 137 | This query will return the total number of rows in the table. 138 | 139 | You can also use the COUNT function with a WHERE clause to count the number of rows that match a specific condition. For example, if you have a table named "customers" with columns "customer_id", "first_name", and "last_name", and you want to count the number of customers whose last name is "Smith", you would use the following query: 140 | 141 | 142 | SELECT COUNT(*) FROM customers WHERE last_name = 'Smith'; 143 | This query will return the number of rows in the "customers" table where the last name is "Smith". 144 | 145 | Note that the COUNT function does not count NULL values unless you use the COUNT(*) syntax. In addition, you can use the COUNT function with other functions such as AVG, SUM, and MAX to perform more complex calculations on the data. 146 | 147 | 148 | # SUM 149 | In MySQL, the SUM function is used to calculate the sum of values in a specific column of a table. It is often used in combination with the SELECT statement to retrieve the total value of a specific column. 150 | 151 | The basic syntax for using the SUM function is as follows: 152 | 153 | SELECT SUM(column_name) FROM table_name; 154 | Here, column_name is the name of the column for which you want to calculate the sum, and table_name is the name of the table containing that column. 155 | 156 | For example, if you have a table named "sales" with columns "product_name" and "sales_amount", and you want to calculate the total sales amount for all products, you would use the following query: 157 | 158 | SELECT SUM(sales_amount) FROM sales; 159 | This query will return the total sales amount for all products in the "sales" table. 160 | 161 | Note that the SUM function only works on numerical data types such as INT, FLOAT, and DECIMAL. It cannot be used with non-numeric data types such as VARCHAR or TEXT. 162 | 163 | 164 | # AVG 165 | In MySQL, the AVG function is used to calculate the average value of a specific column in a table. It is often used in combination with the SELECT statement to retrieve the average value of a specific column. 166 | 167 | The basic syntax for using the AVG function is as follows: 168 | 169 | SELECT AVG(column_name) FROM table_name; 170 | Here, column_name is the name of the column for which you want to calculate the average, and table_name is the name of the table containing that column. 171 | 172 | For example, if you have a table named "students" with columns "student_id", "name", and "score", and you want to calculate the average score for all students, you would use the following query: 173 | 174 | SELECT AVG(score) FROM students; 175 | This query will return the average score for all students in the "students" table. 176 | 177 | Note that the AVG function only works on numerical data types such as INT, FLOAT, and DECIMAL. It cannot be used with non-numeric data types such as VARCHAR or TEXT. 178 | 179 | 180 | # GROUP BY 181 | In MySQL, the GROUP BY clause is used in a SELECT statement to group the result set based on one or more columns. It is often used in combination with aggregate functions such as SUM, COUNT, AVG, MIN, and MAX to perform calculations on groups of data. 182 | 183 | The basic syntax for using the GROUP BY clause is as follows: 184 | 185 | SELECT column_name, aggregate_function(column_name) FROM table_name GROUP BY column_name; 186 | Here, column_name is the name of the column you want to group by, and aggregate_function is the function you want to use to perform calculations on the grouped data. 187 | 188 | For example, if you have a table named "sales" with columns "product_name", "sales_amount", and "sales_date", and you want to calculate the total sales amount for each product, you would use the following query: 189 | 190 | SELECT product_name, SUM(sales_amount) 191 | FROM sales 192 | GROUP BY product_name; 193 | This query will return the total sales amount for each product in the "sales" table. 194 | 195 | Note that when using the GROUP BY clause, the result set will contain one row for each group, rather than one row for each record in the table. Also, any columns that are not included in the GROUP BY clause must be included in an aggregate function. 196 | 197 | 198 | # HAVING 199 | In MySQL, the HAVING clause is used in a SELECT statement to filter the result set based on aggregate function values. It is often used in combination with the GROUP BY clause to filter groups of data based on specific criteria. 200 | 201 | The basic syntax for using the HAVING clause is as follows: 202 | 203 | SELECT column_name, aggregate_function(column_name) 204 | FROM table_name 205 | GROUP BY column_name 206 | HAVING condition; 207 | Here, condition is the filtering condition that the result set must meet in order to be included in the query result. 208 | 209 | For example, if you have a table named "sales" with columns "product_name", "sales_amount", and "sales_date", and you want to find the products that have sold more than $10,000, you would use the following query: 210 | 211 | SELECT product_name, SUM(sales_amount) 212 | FROM sales 213 | GROUP BY product_name 214 | HAVING SUM(sales_amount) > 10000; 215 | This query will return the product names and their total sales amounts for products that have sold more than $10,000. 216 | 217 | Note that the HAVING clause is applied after the GROUP BY clause, so it can only be used with aggregate functions such as SUM, COUNT, AVG, MIN, and MAX. Also, any columns that are not included in the GROUP BY clause must be included in an aggregate function or in the HAVING clause. -------------------------------------------------------------------------------- /DBMS/SQL3/SQL3.md: -------------------------------------------------------------------------------- 1 | ## Joins 2 | 3 | Joins: 4 | 5 | - Right, Left, Inner and Outer Join + Self Join 6 | 7 | - Inner Join: returns only the matching rows from both tables. 8 | 9 | ```sql 10 | SELECT * FROM table1 INNER JOIN table2 ON table1.column = table2.column; 11 | ``` 12 | 13 | - Left Join: returns all the rows from the left table and matching rows from the right table. 14 | 15 | ```sql 16 | SELECT * FROM table1 LEFT JOIN table2 ON table1.column = table2.column; 17 | ``` 18 | 19 | - Right Join: returns all the rows from the right table and matching rows from the left table. 20 | ```sql 21 | SELECT * FROM table1 RIGHT JOIN table2 ON table1.column = table2.column; 22 | ``` 23 | 24 | - Outer Join: returns all the rows from both tables, with NULL values for non-matching rows. 25 | ```sql 26 | SELECT * FROM table1 OUTER JOIN table2 ON table1.column = table2.column; 27 | ``` 28 | 29 | - Self Join: joins a table to itself using an alias. 30 | ```sql 31 | SELECT * FROM table1 AS t1 INNER JOIN table1 AS t2 ON t1.column = t2.column; 32 | ``` 33 | 34 | - USING clause: when both tables have the same connecting column name. 35 | ```sql 36 | SELECT * FROM table1 INNER JOIN table2 USING (column); 37 | ``` 38 | 39 | - Cartesian Product: join without a condition, returns every row from the first table matched with every row from the second table. 40 | ```sql 41 | SELECT * FROM table1, table2; 42 | ``` 43 | 44 | **Example:** 45 | 46 | ```sql 47 | SELECT * FROM Actors INNER JOIN DigitalAssets ON Actors.Id = DigitalAssets.Id; 48 | SELECT * FROM Actors LEFT JOIN DigitalAssets ON Actors.Id = DigitalAssets.Id; 49 | SELECT * FROM Actors RIGHT JOIN DigitalAssets ON Actors.Id = DigitalAssets.Id; 50 | SELECT FirstName, DoB, URL FROM Actors LEFT JOIN DigitalAssets USING(Id); 51 | ``` 52 | 53 | **SELF JOIN:** 54 | - A table is joined with itself using an alias to compare values in a column to other values in the same column. 55 | - Used to find hierarchical relationships between rows in a single table. 56 | 57 | Example: 58 | ```sql 59 | SELECT t1.employee_name, t2.employee_name AS manager_name FROM table1 AS t1 INNER JOIN table1 AS t2 ON t1.manager_id = t2.id; 60 | ``` -------------------------------------------------------------------------------- /DBMS/SQL3/SQL3_JOIN.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/DBMS/SQL3/SQL3_JOIN.pdf -------------------------------------------------------------------------------- /DBMS/sNormalisation Part 2/Black Paper Landscape (12) 2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/DBMS/sNormalisation Part 2/Black Paper Landscape (12) 2.pdf -------------------------------------------------------------------------------- /DBMS/sNormalisation Part 2/Normalization Part_2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/DBMS/sNormalisation Part 2/Normalization Part_2.pdf -------------------------------------------------------------------------------- /DBMS/sNormalisation Part 2/Normalization-II.md: -------------------------------------------------------------------------------- 1 | ## Normalisation - II 2 | 3 | - What is Normalisation? 4 | - It is the process of determining how much redundancy exist in a table & it gives us techniques to reduce it. 5 | - Normal Forms 6 | - 1NF 7 | - 2NF 8 | - 2NF 9 | - BCNF 10 | - First Normal Form / 1NF 11 | - Any attribute must only contain atomic values. 12 | - Second Normal Form / 2NF 13 | - The table should not have partial dependency, and the table should be already in 1NF. 14 | - 3rd Normal Form / 3NF 15 | - The table should be in 2ND and it should not have transitive dependency. 16 | 17 | ### What is Normalization? 18 | 19 | Normalization is the process of determining how much redundancy exists in a table and provides techniques to reduce it. For example, if you have a table with columns for `order_id`, `customer_id`, `customer_name`, and `order_date`, there might be redundancy because the same customer name is repeated for each order by that customer. Normalization can help you reduce this redundancy by splitting the data into two tables: one for orders and one for customers. 20 | 21 | **Normal Forms include 1NF, 2NF, 3NF, and BCNF.** 22 | 23 | - **First Normal Form (1NF)** requires that any attribute must only contain atomic values. For example, if you have a table with a column for `phone_numbers`, it should not contain multiple phone numbers separated by commas. Instead, each phone number should be stored in a separate row. 24 | - **Second Normal Form (2NF)** requires that the table should not have partial dependency and should already be in 1NF. For example, if you have a table with columns for `order_id`, `customer_id`, `customer_name`, and `order_date`, there is a partial dependency because the `customer_name` column depends only on the `customer_id` column and not on the whole primary key (`order_id`, `customer_id`). To bring the table to 2NF, you could split it into two tables: one for orders and one for customers. 25 | - **Third Normal Form (3NF)** requires that the table should be in 2NF and should not have transitive dependency. For example, if you have a table with columns for `order_id`, `customer_id`, `customer_address`, and `order_date`, there is a transitive dependency because the `customer_address` column depends on the `customer_id` column which in turn depends on the primary key (`order_id`). To bring the table to 3NF, you could split it into two tables: one for orders and one for customers. 26 | 27 | 28 | Example - a database for an online store that sells books. We have information about customers, orders, and books. 29 | 30 | We can start by creating three tables: `Customers`, `Orders`, and `Books`. 31 | 32 | The `Customers` table could have columns for `customer_id` (primary key), `first_name`, `last_name`, and `email`. This table is in 1NF because all attributes contain atomic values. It’s also in 2NF and 3NF because there are no partial or transitive dependencies. 33 | 34 | The `Orders` table could have columns for `order_id` (primary key), `customer_id` (foreign key), and `order_date`. This table is also in 1NF, 2NF, and 3NF. 35 | 36 | The `Books` table could have columns for `book_id` (primary key), `title`, `author`, and `price`. This table is also in 1NF, 2NF, and 3NF. 37 | 38 | To represent the relationship between orders and books (i.e., which books are included in each order), we could create another table called `Order_Items` with columns for `order_id` (foreign key), `book_id` (foreign key), and `quantity`. This table is also in 1NF, 2NF, and 3NF. 39 | 40 | Sure! Here are some markdown tables with dummy data for the tables you provided: 41 | 42 | **Customers** 43 | 44 | | customer_id | first_name | last_name | email | 45 | |-------------|------------|-----------|-------| 46 | | 1 | Alice | Smith | alice@example.com | 47 | | 2 | Bob | Johnson | bob@example.com | 48 | | 3 | Charlie | Williams | charlie@example.com | 49 | 50 | **Orders** 51 | 52 | | order_id | customer_id | order_date | 53 | |----------|-------------|------------| 54 | | 1 | 1 | 2022-01-01 | 55 | | 2 | 2 | 2022-01-02 | 56 | | 3 | 3 | 2022-01-03 | 57 | 58 | **Books** 59 | 60 | | book_id | title | author | price | 61 | |---------|-------------|------------|-------| 62 | | 1 | Book A | Author A | 10.99 | 63 | | 2 | Book B | Author B | 12.99 | 64 | | 3 | Book C | Author C | 14.99 | 65 | 66 | **Order_Items** 67 | 68 | | order_id | book_id | quantity | 69 | |----------|---------|----------| 70 | | 1 | 1 | 1 | 71 | | 1 | 2 | 2 | 72 | | 2 | 3 | 1 | 73 | | 3 | 1 | 1 | 74 | | 3 | 2 | 1 | 75 | | 3 | 3 | 1 | 76 | 77 | 78 | ```sql 79 | CREATE TABLE Customers ( 80 | customer_id INTEGER PRIMARY KEY, 81 | first_name TEXT NOT NULL, 82 | last_name TEXT NOT NULL, 83 | email TEXT NOT NULL 84 | ); 85 | 86 | CREATE TABLE Orders ( 87 | order_id INTEGER PRIMARY KEY, 88 | customer_id INTEGER NOT NULL, 89 | order_date DATE NOT NULL, 90 | FOREIGN KEY (customer_id) REFERENCES Customers(customer_id) 91 | ); 92 | 93 | CREATE TABLE Books ( 94 | book_id INTEGER PRIMARY KEY, 95 | title TEXT NOT NULL, 96 | author TEXT NOT NULL, 97 | price NUMERIC NOT NULL 98 | ); 99 | 100 | CREATE TABLE Order_Items ( 101 | order_id INTEGER NOT NULL, 102 | book_id INTEGER NOT NULL, 103 | quantity INTEGER NOT NULL, 104 | FOREIGN KEY (order_id) REFERENCES Orders(order_id), 105 | FOREIGN KEY (book_id) REFERENCES Books(book_id) 106 | ); 107 | ``` 108 | 109 | ## Normalisation - III & Design Schema 110 | 111 | ### Design a db for a Quora like app 112 | 113 | - User should be able to post a question 114 | - User should be able to answer a question 115 | - User should be able to comment on an answer 116 | - User should be able to comment on a comment 117 | - User should be able to like a comment or a question or an answer 118 | - User should be able to follow another user 119 | - Every question can belong to multiple topics 120 | - User can follow a topic also 121 | - You should be able to filter out questions based on topic 122 | 123 | 124 | #### Users Table 125 | | Column Name | Data Type | 126 | | --- | --- | 127 | | user\_id | integer | 128 | | username | varchar | 129 | | email | varchar | 130 | | ... | ... | 131 | 132 | #### Questions Table 133 | | Column Name | Data Type | 134 | | --- | --- | 135 | | question\_id | integer | 136 | | user\_id | integer | 137 | | title | varchar | 138 | | description | text | 139 | | created\_at | timestamp | 140 | | ... | ... | 141 | 142 | #### Answers Table 143 | | Column Name | Data Type | 144 | | --- | --- | 145 | | answer\_id | integer | 146 | | question\_id | integer | 147 | | user\_id | integer | 148 | | content | text | 149 | | created\_at | timestamp | 150 | | ... | ... | 151 | 152 | #### Comments Table 153 | | Column Name | Data Type | 154 | | --- | --- | 155 | | comment\_id | integer | 156 | | parent\_id | integer | 157 | | user\_id | integer | 158 | | content | text | 159 | | created\_at | timestamp | 160 | | ... | ... | 161 | 162 | #### Likes Table 163 | | Column Name | Data Type | 164 | | --- | --- | 165 | | like\_id | integer | 166 | | user\_id | integer | 167 | | content\_type | varchar | 168 | | content\_id | integer | 169 | | ... | ... | 170 | 171 | #### Follows Table 172 | | Column Name | Data Type | 173 | | --- | --- | 174 | | follow\_id | integer | 175 | | follower\_id | integer | 176 | | followee\_id | integer | 177 | | ... | ... | 178 | 179 | #### Topics Table 180 | | Column Name | Data Type | 181 | | --- | --- | 182 | | topic\_id | integer | 183 | | name | varchar | 184 | | ... | ... | 185 | 186 | #### QuestionTopics Table 187 | | Column Name | Data Type | 188 | | --- | --- | 189 | | question\_topic\_id | integer | 190 | | question\_id | integer | 191 | | topic\_id | integer | 192 | | ... | ... | 193 | 194 | #### TopicFollows Table 195 | | Column Name | Data Type | 196 | | --- | --- | 197 | | topic\_follow\_id | integer | 198 | | user\_id | integer | 199 | | topic\_id | integer | 200 | | ... | ... | 201 | 202 | ### Prime attribute & Non prime attribute 203 | 204 | In the context of database design and normalization, a **prime attribute** is an attribute that is part of a candidate key of a relation. A **non-prime attribute** is an attribute that is not part of any candidate key. 205 | 206 | For example, let’s say we have a relation `Student` with attributes `student_id`, `name`, `email`, and `phone`. Let’s assume that `student_id` is unique for each student and can be used to identify a student. In this case, `student_id` is a candidate key for the relation `Student`. Since `student_id` is part of a candidate key, it is a prime attribute. The other attributes (`name`, `email`, and `phone`) are not part of any candidate key and are therefore non-prime attributes. 207 | 208 | In summary, prime attributes are part of candidate keys and can be used to uniquely identify a tuple in a relation. Non-prime attributes are not part of any candidate key and cannot be used to uniquely identify a tuple. 209 | 210 | ### BCNF form 211 | 212 | BCNF (Boyce-Codd Normal Form) is an advanced version of the Third Normal Form (3NF). A table is in BCNF if for every functional dependency X → Y, X is the super key of the table1. 213 | 214 | Here’s an example to help you understand BCNF better: 215 | 216 | Consider a relation R(A, B, C) with functional dependencies {A → BC, B → A}. In this relation, both A and B are super keys so the relation is in BCNF 217 | 218 | Sure! Here's an example with tables to help you understand BCNF better: 219 | 220 | Consider a college enrollment table with columns `student_id`, `subject`, and `professor`. 221 | 222 | | student_id | subject | professor | 223 | |------------|---------|-----------| 224 | | 101 | Java | P.Java | 225 | | 101 | C++ | P.Cpp | 226 | | 102 | Java | P.Java2 | 227 | | 103 | C# | P.Chash | 228 | | 104 | Java | P.Java | 229 | 230 | In this table, one student can enroll for multiple subjects. For each subject, a professor is assigned to the student. And there can be multiple professors teaching one subject like we have for Java. 231 | 232 | `student_id` and `subject` together form the primary key because using `student_id` and `subject`, we can find all the columns of the table. One professor teaches only one subject, but one subject may have two different professors. Hence, there is a dependency between `subject` and `professor` here, where `subject` depends on the professor's name. 233 | 234 | This table satisfies the 1st Normal Form because all the values are atomic, column names are unique and all the values stored in a particular column are of the same domain. This table also satisfies the 2nd Normal Form as there is no Partial Dependency. And there is no Transitive Dependency, hence the table also satisfies the 3rd Normal Form. 235 | 236 | But this table is not in Boyce-Codd Normal Form (BCNF). In the table above, `student_id` and `subject` form the primary key, which means the `subject` column is a prime attribute. But there is one more dependency: `professor → subject`. And while `subject` is a prime attribute, `professor` is a non-prime attribute, which is not allowed by BCNF. 237 | 238 | To make this relation (table) satisfy BCNF, we will decompose this table into two tables: a student table and a professor table. 239 | 240 | Sure! To make the college enrollment table satisfy BCNF, we will decompose it into two tables: a student table and a professor table. 241 | 242 | The student table will have columns `student_id` and `subject`: 243 | 244 | | student_id | subject | 245 | |------------|---------| 246 | | 101 | Java | 247 | | 101 | C++ | 248 | | 102 | Java | 249 | | 103 | C# | 250 | | 104 | Java | 251 | 252 | The professor table will have columns `subject` and `professor`: 253 | 254 | | subject | professor | 255 | |---------|-----------| 256 | | Java | P.Java | 257 | | C++ | P.Cpp | 258 | | Java | P.Java2 | 259 | | C# | P.Chash | 260 | 261 | Now both tables are in BCNF. 262 | 263 | ### 4NF 264 | 265 | Fourth Normal Form (4NF) is an extension of Boyce-Codd Normal Form (BCNF). A relation is in 4NF if it satisfies the following conditions: 266 | - It is in BCNF. 267 | - It does not have any multi-valued dependency². 268 | 269 | A multi-valued dependency occurs when an attribute depends on another attribute, but not on the key of the relation. For a multi-valued dependency to occur there must be at least 3 columns in the relation. If X → Y exists in a relation R (X, Y, Z) then Y and Z should be independent of each other². 270 | 271 | Here's an example to help you understand 4NF better: 272 | 273 | Consider a table `Student` that contains the following records: 274 | 275 | | Stu_Id | Stu_Course | Stu_Hobby | 276 | |--------|------------|-----------| 277 | | 101 | C++ | Reading | 278 | | 101 | C++ | Writing | 279 | 280 | A student can join more than one course. Let's say student with `Stu_Id` 101 joins another course "Java". For a new course, instead of one row, two rows need to be added. 281 | 282 | | Stu_Id | Stu_Course | Stu_Hobby | 283 | |--------|------------|-----------| 284 | | 101 | C++ | Reading | 285 | | 101 | C++ | Writing | 286 | | 101 | Java | Reading | 287 | | 101 | Java | Writing | 288 | 289 | This relation has a multi-valued dependency as `Stu_Id → Stu_Course`, meaning student course is dependent on student id and for each student id, there are multiple courses. Also, `Stu_Course` and `Stu_Hobby` are independent of each other. 290 | 291 | This table has unnecessary records as for each new course, more than one record needs to be added to the table. Let's decompose this table into 4NF: 292 | 293 | This table is already in BCNF. We just need to remove the multi-valued dependency. Let's decompose the original table into two tables. 294 | 295 | Table 1: Course 296 | 297 | | Stu_Id | Stu_Course | 298 | |--------|------------| 299 | | 101 | C++ | 300 | | 101 | Java | 301 | 302 | Table 2: Hobby 303 | 304 | | Stu_Id | Stu_Hobby | 305 | |--------|-----------| 306 | | 101 | Reading | 307 | | 101 | Writing | 308 | 309 | These tables are in 4NF as the multi-valued dependency is removed². 310 | 311 | ### Design a database for a Quora-like app 312 | 313 | - User should be able to post a question 314 | - User should be able to answer a question 315 | - User should be able to comment on an answer 316 | - User should be able to comment on a comment 317 | - User should be able to like a comment or a question or an answer 318 | - User should be able to follow another user 319 | - Every question can belong to multiple topics 320 | - User can follow a topic also 321 | - You should be able to filter out questions based on topic 322 | 323 | #### Users Table 324 | | Column Name | Data Type | 325 | | --- | --- | 326 | | user\_id | integer | 327 | | username | varchar | 328 | | email | varchar | 329 | | ... | ... | 330 | 331 | 332 | #### Questions Table 333 | 334 | | Column Name | Data Type | 335 | | --- | --- | 336 | | question\_id | integer | 337 | | user\_id | integer | 338 | | title | varchar | 339 | | description | text | 340 | | created\_at | timestamp | 341 | | ... | ... | 342 | 343 | 344 | #### Answers Table 345 | 346 | | Column Name | Data Type | 347 | | --- | --- | 348 | | answer\_id | integer | 349 | | question\_id | integer | 350 | | user\_id | integer | 351 | | content | text | 352 | | created\_at | timestamp | 353 | | ... | ... | 354 | 355 | 356 | #### Comments Table 357 | 358 | | Column Name | Data Type | 359 | | --- | --- | 360 | | comment\_id | integer | 361 | | parent\_id | integer | 362 | | user\_id | integer | 363 | | content | text | 364 | | created\_at | timestamp | 365 | | ... | ... | 366 | 367 | 368 | #### Likes Table 369 | 370 | 371 | | Column Name | Data Type | 372 | | --- | --- | 373 | | like\_id | integer | 374 | | user\_id | integer | 375 | | content\_type | varchar | 376 | | content\_id | integer | 377 | | ... | ... | 378 | 379 | 380 | #### Follows Table 381 | 382 | 383 | | Column Name | Data Type | 384 | | --- | --- | 385 | | follow\_id | integer | 386 | | follower\_id | integer | 387 | | followee\_id | integer | 388 | | ... | ... | 389 | 390 | 391 | #### Topics Table 392 | 393 | 394 | | Column Name | Data Type | 395 | | --- | --- | 396 | | topic\_id | integer | 397 | | name | varchar | 398 | | ... | ... | 399 | 400 | 401 | #### QuestionTopics Table 402 | 403 | 404 | | Column Name | Data Type | 405 | | --- | --- | 406 | | question\_topic\_id | integer | 407 | | question\_id | integer | 408 | | topic\_id | integer | 409 | | ... | ... | 410 | 411 | 412 | #### TopicFollows Table 413 | 414 | 415 | | Column Name | Data Type | 416 | | --- | --- | 417 | | topic\_follow\_id | integer | 418 | | user\_id | integer | 419 | | topic\_id | integer | 420 | | ... | ... | 421 | 422 | ### Design a movie booking application DB 423 | 424 | - User can book a movie on a particular theatre and timings 425 | - User can review a movie 426 | - User can review a theatre 427 | - Review involves rating and comments both 428 | - You can cancel a booking / or if your payment is stuck then booking can be pending else confirmed 429 | - You should be able to get all movies from a theatre 430 | - You should be able to get all theatres of a particular city where movie is running 431 | 432 | 433 | #### Users 434 | 435 | A table to store user information such as user\_id, name, email, password, etc. 436 | 437 | | Column Name | Data Type | Description | 438 | | --- | --- | --- | 439 | | user\_id | integer | Unique identifier for each user | 440 | | name | varchar | User's name | 441 | | email | varchar | User's email address | 442 | | password | varchar | User's password | 443 | | ... | ... | Other user information | 444 | 445 | 446 | #### Theatres 447 | 448 | A table to store theatre information such as theatre\_id, name, city, address, etc. 449 | 450 | | Column Name | Data Type | Description | 451 | | --- | --- | --- | 452 | | theatre\_id | integer | Unique identifier for each theatre | 453 | | name | varchar | Name of the theatre | 454 | | city | varchar | City where the theatre is located | 455 | | address | varchar | Address of the theatre | 456 | | ... | ... | Other theatre information | 457 | 458 | 459 | #### Movies 460 | 461 | A table to store movie information such as movie\_id, name, description, etc. 462 | 463 | | Column Name | Data Type | Description | 464 | | --- | --- | --- | 465 | | movie\_id | integer | Unique identifier for each movie | 466 | | name | varchar | Name of the movie | 467 | | description | varchar | Description of the movie | 468 | | ... | ... | Other movie information | 469 | 470 | 471 | #### TheatreMovies 472 | 473 | A table to store the relationship between theatres and movies with columns such as theatre\_movie\_id, theatre\_id, and movie\_id. 474 | 475 | | Column Name | Data Type | Description | 476 | | --- | --- | --- | 477 | | theatre\_movie\_id | integer | Unique identifier for each theatre-movie relationship | 478 | | theatre\_id | integer | Identifier for the theatre | 479 | | movie\_id | integer | Identifier for the movie | 480 | | ... | ... | Other theatre-movie relationship information | 481 | 482 | #### Showtimes 483 | 484 | A table to store showtime information such as showtime\_id, theatre\_id, movie\_id, start\_time, end\_time, etc. 485 | 486 | | Column Name | Data Type | Description | 487 | | --- | --- | --- | 488 | | showtime\_id | integer | Unique identifier for each showtime | 489 | | theatre\_id | integer | Identifier for the theatre | 490 | | movie\_id | integer | Identifier for the movie | 491 | | start\_time | datetime | Start time of the show | 492 | | end\_time | datetime | End time of the show | 493 | | ... | ... | Other showtime information | 494 | 495 | 496 | #### Bookings 497 | 498 | A table to store booking information such as booking\_id, user\_id, showtime\_id, status, payment\_status, etc. 499 | 500 | | Column Name | Data Type | Description | 501 | | --- | --- | --- | 502 | | booking\_id | integer | Unique identifier for each booking | 503 | | user\_id | integer | Identifier for the user | 504 | | showtime\_id | integer | Identifier for the showtime | 505 | | status | varchar | Status of the booking (confirmed, cancelled, pending) | 506 | | payment\_status | varchar | Status of the payment (paid, pending) | 507 | | ... | ... | Other booking information | 508 | 509 | 510 | #### Reviews 511 | 512 | A table to store review information such as review\_id, user\_id, movie\_id, theatre\_id, rating, comment, etc. 513 | | Column Name | Data Type | Description | 514 | | --- | --- | --- | 515 | | review\_id | integer | Unique identifier for each review | 516 | | user\_id | integer | Identifier for the user | 517 | | movie\_id | integer | Identifier for the movie | 518 | | theatre\_id | integer | Identifier for the theatre | 519 | | rating | integer | Rating given by the user (out of 5) | 520 | | comment | varchar | Comment given by the user | 521 | | ... | ... | Other review information | 522 | 523 | 524 | With this design, you can easily perform operations such as booking a movie, reviewing a movie or theatre, cancelling a booking, getting all movies from a theatre, 525 | 526 | ## Triggers & Joins (Lecture) 527 | 528 | - A practical lecture, Please refer to live lecture. 529 | - Refer this link for Database. 530 | - github.com/hhorak/mysql-sample-db/blob/master/mysqlsampledatabase.sql -------------------------------------------------------------------------------- /DBMS/sNormalisation Part 3/Black Paper Landscape (13).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/DBMS/sNormalisation Part 3/Black Paper Landscape (13).pdf -------------------------------------------------------------------------------- /DBMS/sNormalisation Part 3/hw.md: -------------------------------------------------------------------------------- 1 | ## Design a movie booking application db 2 | 3 | - User can book a movie on a particular theatre and timings 4 | - User can review a movie 5 | - User can review a theatre 6 | - Review involves rating and comments both 7 | - You can cancel a booking / or if your payment is stuck then booking can be pending else confirmed 8 | - You should be able to get all movies from a theatre 9 | - You should be able to get all theatres of a particular city where movie is running 10 | -------------------------------------------------------------------------------- /DBMS/sNormalisation Part 3/requirements.md: -------------------------------------------------------------------------------- 1 | ## Design a db for a quora like app 2 | 3 | - User should be able to post a question 4 | - User should be able to answer a question 5 | - User should be able to comment on an answer 6 | - User should be able to comment on a comment 7 | - User should be able to like a comment or a question or an answer 8 | - User should be able to follow another user 9 | - Every question can belong to multiple topics 10 | - User can follow a topic also 11 | - You should be able to filter out questions based on topic 12 | -------------------------------------------------------------------------------- /JavaScript/Chapter 01 - Operators/Code/AdditionalOperators.js: -------------------------------------------------------------------------------- 1 | let obj = {}; 2 | 3 | console.log(obj); 4 | 5 | console.log("18" + obj); // "18" "[object Object]" -> "18[object Object]" 6 | 7 | console.log(18 + obj); // 18 "[object Object]" -> -------------------------------------------------------------------------------- /JavaScript/Chapter 01 - Operators/Code/ToPrimitives.js: -------------------------------------------------------------------------------- 1 | let obj = {}; 2 | 3 | console.log(10 - obj); // obj.valueOf -> object, toString -> [object Object] 4 | 5 | let obj1 = {x: 9, y: 8}; 6 | 7 | console.log(100 - obj1); 8 | 9 | let obj2 = {x: 7, valueOf() {return 99}}; 10 | console.log(100 - obj2); 11 | 12 | let obj3 = {x: 8, toString() {return "88"}}; 13 | console.log(90 - obj3); 14 | 15 | let obj4 = {x: 7, toString() {return {}}}; 16 | console.log(100 - obj4); -------------------------------------------------------------------------------- /JavaScript/Chapter 01 - Operators/Theory/Operators-Conditionals-Loops-basic.md: -------------------------------------------------------------------------------- 1 | # Introduction to JS 2 | Operators | Conditionals | Loops basic 2 | 3 | - Operators 4 | - Operations 5 | - 1 + 1 → 2 6 | - "1" + 1 → "11" 7 | - "1" - 1 → 0 8 | - Javascript is not weird, it's just people have never read the documentation. 9 | - defined in ECMA Script 10 | - [[Coercion]] → type conversion 11 | - What is Coercion? 12 | - It can be manual or automatic (based on certain algorithms) 13 | - manual → explicit type conversion 14 | - automatic → implicit type conversion 15 | - [[Abstract Operations]] 16 | - These are some set of algorithms, that is present in the ecmascript docs, but they are not available for usage in ecmascript i.e. we as developers cannot use these operation directly. 17 | - They are mentioned in the docs to help the documentation only. 18 | - In the ecma docs there are a lot of things that are done by the language internally. To explain these internal details of how and what language is doing, we have abstract operations mentioned in the docs. 19 | - Type Conversion 20 | - The ECMAScript language implicitly performs automatic type conversion as needed. To clarify the semantics of certain constructs it is useful to define a set of conversion abstract operations. The conversion abstract operations are polymorphic; they can accept a value of any ECMAScript language type. But no other specification types are used with these operations. -------------------------------------------------------------------------------- /JavaScript/Chapter 02 - Introduction To Coersion/Code/AbstractEquality.js: -------------------------------------------------------------------------------- 1 | console.log(null == undefined); 2 | console.log(12 == "12"); 3 | 4 | console.log(false == "0"); 5 | /* 6 | x -> boolean -> ToNumber -> false -> 0 7 | x = 0, y = "0", x == y 8 | y -> ToNumber -> 0 9 | 0 == 0 -> true 10 | */ 11 | 12 | console.log(null == false); 13 | /** 14 | * y -> is a boolean -> ToNumber -> 0 15 | * null == 0 16 | * false 17 | */ 18 | console.log("NaN" == NaN); 19 | 20 | let obj = {x: 10, valueOf() {return 100;}} 21 | 22 | console.log(99 == obj); 23 | console.log(100 == obj); -------------------------------------------------------------------------------- /JavaScript/Chapter 02 - Introduction To Coersion/Code/CoersionExamples.js: -------------------------------------------------------------------------------- 1 | console.log(1 < 2 < 3);// -> (1 < 2) = true -> true < 3 -> 1 < 3 -> true 2 | console.log(3 > 2 > 1);// -> (3 > 2) -> true -> true > 1 -> 1 > 1 -> false 3 | 4 | let obj = {x: 10, y: 20}; 5 | let num = 10; 6 | console.log(`My object is ${obj}`); 7 | console.log("My object is"+obj); -------------------------------------------------------------------------------- /JavaScript/Chapter 02 - Introduction To Coersion/Code/CornerCasesCoersion.js: -------------------------------------------------------------------------------- 1 | // ToString -> "" + value 2 | console.log("" + 0); // 0 -> "0" 3 | console.log("" + (-0)); // -0 -> "0" 4 | 5 | console.log("" + []); // [] -> "" 6 | console.log("" + {}); 7 | 8 | console.log("" + [1,2,3]); 9 | 10 | console.log("" + [null, undefined]); 11 | 12 | console.log("" + [1,2,null, 4]); 13 | 14 | // ToNumber 15 | console.log(0 - "010"); // decimal number 16 | console.log(0 - "O10"); 17 | console.log(0 - 010); // octal number 18 | console.log(0 - "0xb");// hexadecimal number 19 | console.log(0 - 0xb); 20 | 21 | console.log([] - 1); 22 | console.log([""] - 1); 23 | console.log(["0"] - 1); 24 | console.log([6] - 1); -------------------------------------------------------------------------------- /JavaScript/Chapter 02 - Introduction To Coersion/Code/ExplicitConversion.js: -------------------------------------------------------------------------------- 1 | console.log(Boolean("")); 2 | console.log(String(123)); -------------------------------------------------------------------------------- /JavaScript/Chapter 02 - Introduction To Coersion/Code/NaN.js: -------------------------------------------------------------------------------- 1 | console.log(Number("123")); 2 | console.log(Number("abcd")); 3 | console.log(Number("0xa")); 4 | 5 | let x = NaN; 6 | 7 | console.log(x == NaN); 8 | 9 | console.log(isNaN(x)); 10 | 11 | console.log(isNaN("sanket")); // isNaN converts the incoming input to a number 12 | 13 | console.log(Number.isNaN("sanket")); 14 | console.log(Number.isNaN(x)); 15 | 16 | if(typeof(x) == 'number' && x !== x ) { 17 | console.log(true); 18 | } 19 | 20 | console.log(x !== x); // ! == is there any problem with this expression to check nan value -------------------------------------------------------------------------------- /JavaScript/Chapter 02 - Introduction To Coersion/Code/NegativeZeroes.js: -------------------------------------------------------------------------------- 1 | let x = -0; 2 | console.log(x === 0); 3 | console.log(Object.is(x, -0)); // true 4 | console.log(Object.is(x, 0)); // false 5 | 6 | console.log(Math.sign(-3)); 7 | console.log(Math.sign(2)); 8 | console.log(Math.sign(-0)); 9 | console.log(Math.sign(0)); 10 | 11 | console.log(x < 0); 12 | 13 | /* 14 | Can we write a custom function that can give us sign of a number properly ? expected -> -1, 1 15 | */ -------------------------------------------------------------------------------- /JavaScript/Chapter 02 - Introduction To Coersion/Code/StrictEquality.js: -------------------------------------------------------------------------------- 1 | console.log(NaN === NaN); 2 | console.log(0 === -0) 3 | 4 | let obj1 = {x: 10}; 5 | let obj2 = {x: 10}; 6 | let obj3 = {y: 10}; 7 | console.log(obj1 === obj2); 8 | console.log(obj1 === obj3); 9 | console.log(obj1 === obj1); 10 | console.log({x: 10} === {x: 10}); -------------------------------------------------------------------------------- /JavaScript/Chapter 02 - Introduction To Coersion/Code/ToBooleanDemo.js: -------------------------------------------------------------------------------- 1 | let x = 10; 2 | console.log(!x); 3 | let y = undefined; 4 | console.log(!y); 5 | 6 | if(y) { 7 | console.log("It is truthy"); 8 | } else { 9 | console.log("It is falsy"); 10 | } -------------------------------------------------------------------------------- /JavaScript/Chapter 02 - Introduction To Coersion/Coersion,_NaN,_Equality_Operators.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/JavaScript/Chapter 02 - Introduction To Coersion/Coersion,_NaN,_Equality_Operators.pdf -------------------------------------------------------------------------------- /JavaScript/Chapter 02 - Introduction To Coersion/Theory/Coersion.md: -------------------------------------------------------------------------------- 1 | Javascript type coercion 2 | =================== 3 | 4 | ## Javascript types 5 | 6 | The types used in ES5 (currently widely supported JS spec version) 7 | Pirimitives: `String`, `Boolean`, `Number`, `undefined` 8 | Objects: `Object`, with sub-classes at least for `Function`, `Array`, `Date`, `RegExp`, `Error` 9 | Special cases: `Null` 10 | 11 | **Primitives** 12 | A primitive is just a value (String is a 0-x letters, boolean is true or false, numbers are numbers). 13 | 14 | This might not be what you expected, as for ex. strings seem to have methods. They seem to (and for practical purposes you can think they have methods) but strictly speaking they don’t. You’ll see why this is a bit later. 15 | 16 | **Objects** 17 | Objects are objects (surprise!) with a property Class explaining what subclass they inherit their behavior from. Function is basically a callable object. 18 | 19 | **null** 20 | Null is a special case, with the infamous ‘typeof null returns “object”?!?’. Let’s not go there this time. 21 | 22 | ## What is coercion? 23 | 24 | Javascript is a dynamically typed language. Basically this means that *variables don’t have types, values do*. So when a variable is used, JS has to check what type its value is, and then figure out if that type needs to be cast to some other type. 25 | 26 | Sometimes this is handy, for ex. 27 | 28 | var numberOfCows = 10, 29 | outputTxt = ‘We will proceed to catapult ‘ + numberOfCows + ‘ cows.'; 30 | 31 | Type coercion is the reason you didn’t have to write 32 | 33 | outputText = ‘We will proceed to catapult ‘ + String(numberOfCows) + ‘ cows.’; 34 | 35 | This said, in many cases it’s confusing or at worst misleading. Like presented in https://www.destroyallsoftware.com/talks/wat 36 | 37 | #### WAT just happened? 38 | 39 | 40 | Javascript is not a type safe language. 41 | 42 | When javascript expects a certain type for parameter/operand x, and doesn’t get it, it will try to assign x to the type it’s expecting. 43 | 44 | [] + [] == “” // returns true 45 | 46 | Why? Because the plus-operator expects strings or numbers. Which means it will try to coerce the operands to some useful type. If String length is zero, the string will be empty. 47 | 48 | Testing 49 | 50 | [1, 2] + [3] // “1,23” 51 | 52 | Shows more clearly what’s happening. 53 | 54 | ## Why learning about this is important? 55 | Because it’s done in everywhere in JS. To understand JS deeply, you really have to understand how coercion works. At the very least to the level where you understand the “safety measures” you sometimes see used to safeguard against unwanted coercion. The most known of these is probably the often seen advice to avoid == operator. 56 | 57 | But other operators and statements also trigger coercion, like +, -, if, while to mention a few. Understanding the general idea and knowing where to look if you suspect something fishy is happening with your code is useful. This will help you also understand when it’s good to use strict equality === and when == might be more apropriate. 58 | 59 | It’s not black magic. It’s described in the EcmaScript spec (which is a lot more clear than I had feared), and even V8 code is extremely legible. 60 | 61 | ### What triggers type coercion? 62 | Common cases are `==` (aka double equals, or “Abstract equality”), `<`, `>` `<=`, `>=`, `if ()`, `+`, `-`, .. But basically any operation or statement that clearly expects some type will probably go for coercion, and either give you ok, some really weird results (meaning the coercion almost worked), or an error (coercion failed miserably enough). 63 | 64 | `==` is the most complicated one, so we might as well tackle that first. 65 | 66 | ### Abstract Equality (double equals, ==) 67 | 68 | ( 69 | 70 | ## Workarounds for unwanted type coercion 71 | ### Explicit type casting (recommended) 72 | 73 | The syntax should be self-evident from the code. 74 | 75 | x = String(10); // ’10’ 76 | x = Boolean(0) // false 77 | x = Boolean(1) // true 78 | x = Number(’19’) // 19 79 | 80 | ### Checking for strict equality (===), sometimes recommended 81 | Checking for strict equality checks that both the type and value match. So 82 | 83 | 1 === '1' // false 84 | 1 === 1 // true 85 | 1 === {valueOf: function() { return 1; } } // false 86 | 1 === true // false 87 | 88 | compared to 89 | 90 | 1 == '1' // true 91 | 1 == 1 // true 92 | 1 == {valueOf: function() { return 1; } } // true 93 | 1 == true // true 94 | 95 | Most of the time, this is what we want. But sometimes type coercion is practical. 96 | 97 | 98 | ### implicit type casting (not recommended should be understood) 99 | 100 | This is mostly useful for reading code “in the wild”. I prefer explicit casting just because it’s more understandable to people who aren’t familiar with all JS details, and makes very clear when we want a value of a certain type. 101 | 102 | **Cast to String (from number)** 103 | 104 | 10 + “” // 10 105 | 106 | **Cast to String (from array)** 107 | 108 | [1, 2, 3] + “” // “1,2,3” 109 | 110 | **Cast to number (from string)** 111 | 112 | ’10’ - 0 // 10 113 | 114 | **Cast to boolean (From any type)** 115 | 116 | !!10 // true 117 | !!0 // false 118 | !!null // false 119 | !!undefined // false 120 | 121 | but watch out.. 122 | 123 | !![] // true 124 | !!”” // false 125 | 126 | Implicit conversion of objects needs use of overwriting inbuilt `valueOf` or `toString` functions. 127 | for ex. 128 | 129 | 10 * {} // NaN 130 | 10 * { valueOf: function() { return 7; }} // 70 131 | 10 * { toString: function() { return “7”; }} // 70 132 | 133 | `toString` and `valueOf` are important for evaluation of objects, and have their uses in object evaluation, but more on these another time. 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | -------------------------------------------------------------------------------- /JavaScript/Chapter 03 - Scopes and Function Expression/Code/blockscope.js: -------------------------------------------------------------------------------- 1 | { 2 | let x = 10; 3 | } 4 | 5 | console.log(x); -------------------------------------------------------------------------------- /JavaScript/Chapter 03 - Scopes and Function Expression/Code/constdemo.js: -------------------------------------------------------------------------------- 1 | // const x = 10; 2 | // x = 9; 3 | 4 | // const obj = {x: 10}; 5 | // obj.y = 9; 6 | 7 | // obj = {}; 8 | 9 | // const y; -------------------------------------------------------------------------------- /JavaScript/Chapter 03 - Scopes and Function Expression/Code/demo.js: -------------------------------------------------------------------------------- 1 | console.log("hi"); 2 | // console = {lo: function(str) {}} 3 | // console.lo("hello"); 4 | console.log("bye"); 5 | 6 | console.log(5..toString(2)); 7 | 8 | 9 | console.log("hi"); 10 | console..log("hello"); 11 | console.log("bye"); -------------------------------------------------------------------------------- /JavaScript/Chapter 03 - Scopes and Function Expression/Code/function_in_blocks.js: -------------------------------------------------------------------------------- 1 | { 2 | function fun() { 3 | return "123"; 4 | } 5 | } 6 | 7 | console.log(fun); -------------------------------------------------------------------------------- /JavaScript/Chapter 03 - Scopes and Function Expression/Code/function_in_blocks_strict_mode.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | { 3 | function fun() { 4 | return "123"; 5 | } 6 | console.log(fun); 7 | } 8 | 9 | console.log(fun); -------------------------------------------------------------------------------- /JavaScript/Chapter 03 - Scopes and Function Expression/Code/functionexpression.js: -------------------------------------------------------------------------------- 1 | function fun() { // function declaration 2 | // some impl 3 | } 4 | 5 | let f = function gun() { // named function expression 6 | // some impl 7 | } 8 | 9 | let a = function() { // anonymous function expression 10 | // okk some more impl 11 | } 12 | 13 | (function x() { 14 | // can you stop it ? 15 | }) // function expression 16 | 17 | (function (){ 18 | // i am done 19 | }) 20 | 21 | let y = () => { 22 | 23 | } -------------------------------------------------------------------------------- /JavaScript/Chapter 03 - Scopes and Function Expression/Code/functionexpressiondemo.js: -------------------------------------------------------------------------------- 1 | let x = function () { 2 | console.log('HI'); 3 | } 4 | console.log(x); 5 | x(); -------------------------------------------------------------------------------- /JavaScript/Chapter 03 - Scopes and Function Expression/Code/functionscope.js: -------------------------------------------------------------------------------- 1 | if(false){ 2 | var x = 10; 3 | } 4 | 5 | console.log(x); 6 | 7 | function fun() { 8 | console.log(y); // y is accessible here 9 | var y = 10; // not accessible outside 10 | } 11 | 12 | 13 | function gun() { 14 | console.log(z); // not accessible here 15 | let z = 10; 16 | } 17 | //console.log(z); 18 | // gun(); -------------------------------------------------------------------------------- /JavaScript/Chapter 03 - Scopes and Function Expression/Code/globalscope.js: -------------------------------------------------------------------------------- 1 | var name = "Sanket"; 2 | function fun() { 3 | console.log(name); 4 | } 5 | fun(); 6 | console.log(name); -------------------------------------------------------------------------------- /JavaScript/Chapter 03 - Scopes and Function Expression/Code/let_block_scoping.js: -------------------------------------------------------------------------------- 1 | var teacher = "Sanket"; // global 2 | function fun() { // global 3 | console.log(teacher); // no error will be given 4 | // console.log(content); // throws an error 5 | var teacher = "Pulkit"; // scope of fun 6 | let content = "JS"; // content will be access only post declaration 7 | if(content == "JS") { 8 | let hours = "120+"; 9 | console.log(content,hours); 10 | } 11 | console.log(teacher, content); 12 | } 13 | 14 | fun(); 15 | console.log(teacher); 16 | // console.log(content); 17 | 18 | 19 | /** 20 | * 21 | * { 22 | * 23 | * } 24 | */ -------------------------------------------------------------------------------- /JavaScript/Chapter 03 - Scopes and Function Expression/Code/nestedscopes.js: -------------------------------------------------------------------------------- 1 | function fun() { // fun -> global scope 2 | var x = 10; // x -> fun scope 3 | function gun() { // gun -> fun scope 4 | var y = 20; // y -> gun scope 5 | console.log(x); // 10 6 | console.log(y); // 20 7 | } 8 | gun(); 9 | console.log(x); // 10 10 | console.log(y); // error 11 | } 12 | 13 | fun(); -------------------------------------------------------------------------------- /JavaScript/Chapter 03 - Scopes and Function Expression/Code/scopes1.js: -------------------------------------------------------------------------------- 1 | var teacher = "Sanket"; 2 | function fun() { 3 | var teacher = "Pulkit"; 4 | console.log(teacher); 5 | } 6 | function gun() { 7 | var student = "Sarthak"; 8 | console.log(student); 9 | } 10 | 11 | fun(); 12 | gun(); 13 | console.log(teacher); 14 | 15 | 16 | -------------------------------------------------------------------------------- /JavaScript/Chapter 03 - Scopes and Function Expression/Code/scopes2.js: -------------------------------------------------------------------------------- 1 | var teacher = "Sanket"; 2 | function fun() { 3 | var teacher = "Pulkit"; 4 | content = "JS"; 5 | console.log(teacher); 6 | console.log(content); 7 | } 8 | function gun() { 9 | var student = "Sarthak"; 10 | console.log(student); 11 | } 12 | // console.log(content); 13 | fun(); 14 | gun(); 15 | console.log(teacher); 16 | console.log(content); 17 | 18 | const o = { p: 1, p: 2 }; 19 | 20 | -------------------------------------------------------------------------------- /JavaScript/Chapter 03 - Scopes and Function Expression/Code/scopes3.js: -------------------------------------------------------------------------------- 1 | console.log(content); 2 | content = "JS"; -------------------------------------------------------------------------------- /JavaScript/Chapter 03 - Scopes and Function Expression/Code/scopesfunctionexpression.js: -------------------------------------------------------------------------------- 1 | const f = function fun() { 2 | console.log("How much fun????"); 3 | } 4 | 5 | console.log(f()); 6 | // fun();s -------------------------------------------------------------------------------- /JavaScript/Chapter 03 - Scopes and Function Expression/Code/strict_mode_auto_global.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var teacher = "Sanket"; 3 | function fun() { 4 | var teacher = "Pulkit"; 5 | // content = "JS"; 6 | console.log(teacher); 7 | // console.log(content); 8 | } 9 | function gun() { 10 | var student = "Sarthak"; 11 | console.log(student); 12 | } 13 | fun(); 14 | gun(); 15 | console.log(teacher); 16 | // console.log(content); 17 | 18 | 19 | 20 | const o = { p: 1, p: 2 }; -------------------------------------------------------------------------------- /JavaScript/Chapter 03 - Scopes and Function Expression/Code/usecaseofnamedfunctionexpression.js: -------------------------------------------------------------------------------- 1 | function fun(fn) { 2 | console.log("Welcome to fun"); 3 | fn(); 4 | } 5 | 6 | fun(function () { 7 | console.log("Wow so much fun"); 8 | console.trace(); 9 | }); 10 | 11 | 12 | // for recursive cases named function expression are also helpful -------------------------------------------------------------------------------- /JavaScript/Chapter 03 - Scopes and Function Expression/Code/usecasevar.js: -------------------------------------------------------------------------------- 1 | function fun(x) { 2 | let i; // var i 3 | if(x %2 == 0) { 4 | i = 0; 5 | } else { 6 | i = 1; 7 | } 8 | } 9 | 10 | function gun(x) { 11 | if(x %2 == 0) { 12 | var i = 0; 13 | } else { 14 | var i = 1; 15 | } 16 | console.log(i); 17 | } 18 | 19 | gun(10); -------------------------------------------------------------------------------- /JavaScript/Chapter 03 - Scopes and Function Expression/Code/useccaselet.js: -------------------------------------------------------------------------------- 1 | function fun() { 2 | for(let i = 0; i < 10; i++) { 3 | // do something 4 | } 5 | console.log(i); 6 | } 7 | 8 | function process(x, y) { 9 | if(x > y) { 10 | // var temp = x; 11 | let temp = x; 12 | x = y; 13 | y = temp; 14 | } 15 | return y - x; 16 | } 17 | 18 | fun(); -------------------------------------------------------------------------------- /JavaScript/Chapter 03 - Scopes and Function Expression/Code/var_in_block.js: -------------------------------------------------------------------------------- 1 | function fun() { 2 | var i = 5; 3 | while(i < 10) { 4 | var x = i; 5 | i++; 6 | } 7 | console.log(x); 8 | } 9 | fun(); 10 | let i = 1; 11 | console.log(y); 12 | while(i < 5) { 13 | var y = 10; 14 | i++; 15 | } 16 | console.log(y); 17 | // redeclaration is not allowed with let, but it is allowed with var 18 | // let x = 9; 19 | // let x = 10; -------------------------------------------------------------------------------- /JavaScript/Chapter 03 - Scopes and Function Expression/Code/whichscoping.js: -------------------------------------------------------------------------------- 1 | // var teacher = "Sanket"; 2 | // function ask(question) { 3 | // console.log(teacher, question); 4 | // } 5 | 6 | // function fun() { 7 | // var teacher = "Pulkit"; 8 | // ask("why?"); 9 | // } 10 | // fun(); 11 | var fun; 12 | function fun() { 13 | return 'fun2'; 14 | } 15 | 16 | console.log(fun); -------------------------------------------------------------------------------- /JavaScript/Chapter 03 - Scopes and Function Expression/Theory/Function-Expression.md: -------------------------------------------------------------------------------- 1 | ## Function Expression 2 | 3 | ```js 4 | var teacher = "Sanket"; // global 5 | function fun() { // global 6 | console.log(teacher); // no error will be given 7 | // console.log(content); // throws an error 8 | var teacher = "Pulkit"; // scope of fun 9 | let content = "JS"; // content will be access only post declaration 10 | if(content == "JS") { 11 | let hours = "120+"; 12 | console.log(content,hours); 13 | } 14 | console.log(teacher, content); 15 | } 16 | 17 | fun(); 18 | console.log(teacher); 19 | // console.log(content); 20 | ``` 21 | 22 | - `let` in javascript 23 | - The **`let`** declaration declares a block-scoped local variable, optionally initializing it to a value. 24 | - How do you create a block? 25 | - { } 26 | - Scope determines the accessibility (visibility) of variables. 27 | - JavaScript has 3 types of scope: 28 | - **Block scope** 29 | - **Function scope** 30 | - **Global scope** 31 | - Function scope is within the function. 32 | - Block scope is within curly brackets. 33 | 34 | ```js 35 | var character4 = 36 | function foo() { 37 | if(true) { 38 | var character1 = "Robin" //function scope 39 | let character2 = "Ted" //block scope 40 | const character3 = "Barney" //block scope 41 | } 42 | console.log(character1) //Robin 43 | console.log(character2) //not defined 44 | console.log(character3). //not defined 45 | } 46 | ``` 47 | 48 | - Difference between function scope and block scope? 49 | - **Function Scope**: When a variable is declared inside a function, it is only accessible within that function and cannot be used outside that function. 50 | - **Block Scope**: A variable when declared inside the if or switch conditions or inside for or while loops, are accessible within that particular condition or loop. To be concise, the variables declared inside the curly braces are called within the block scope. 51 | - `let` is accessible in sub blocks. 52 | - [Demystifying JavaScript Variable Scope and Hoisting — SitePoint](https://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/) 53 | - In JavaScript, variables with the same name can be specified at multiple layers of nested scope. In such case local variables gain priority over global variables. If you declare a local variable and a global variable with the same name, the local variable will take precedence when you use it inside a function. This type of behavior is called shadowing. Simply put, the inner variable shadows the outer. 54 | - [Is this an example of variable shadowing in JavaScript? - Stack Overflow](https://stackoverflow.com/a/11901489/6375464) 55 | - In computer programming, variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. This outer variable is said to be shadowed... 56 | - What is Temporal Dead Zone? 57 | - Temporal Dead Zone is **the period of time during which the let and const declarations cannot be accessed**. Temporal Dead Zone starts when the code execution enters the block which contains the let or const declaration and continues until the declaration has executed. 58 | - It the region before the declaration of the block scope variable. 59 | - Suppose you attempt to access a variable before its complete initialization. In such a case, JavaScript will throw a `ReferenceError`. 60 | 61 | **Where Exactly Is the Scope of a Temporal Dead Zone?** 62 | 63 | A block’s temporal dead zone starts at the beginning of the block’s local scope. It ends when the computer fully initializes your variable with a value. 64 | 65 | **Here’s an example:** 66 | 67 | ```js 68 | { 69 | // bestFood’s TDZ starts here (at the beginning of this block’s local scope) 70 | // bestFood’s TDZ continues here 71 | // bestFood’s TDZ continues here 72 | // bestFood’s TDZ continues here 73 | console.log(bestFood); // returns ReferenceError because bestFood’s TDZ continues here 74 | // bestFood’s TDZ continues here 75 | // bestFood’s TDZ continues here 76 | let bestFood = "Vegetable Fried Rice"; // bestFood’s TDZ ends here 77 | // bestFood’s TDZ does not exist here 78 | // bestFood’s TDZ does not exist here 79 | // bestFood’s TDZ does not exist here 80 | } 81 | ``` 82 | 83 | Now, consider this example: 84 | 85 | ```js 86 | { 87 | // TDZ starts here (at the beginning of this block’s local scope) 88 | // bestFood’s TDZ continues here 89 | // bestFood’s TDZ continues here 90 | // bestFood’s TDZ continues here 91 | // bestFood’s TDZ continues here 92 | // bestFood’s TDZ continues here 93 | // bestFood’s TDZ continues here 94 | let bestFood; // bestFood’s TDZ ends here 95 | console.log(bestFood); // returns undefined because bestFood’s TDZ does not exist here 96 | bestFood = "Vegetable Fried Rice"; // bestFood’s TDZ does not exist here 97 | console.log(bestFood); // returns "Vegetable Fried Rice" because bestFood’s TDZ does not exist here 98 | } 99 | ``` 100 | 101 | **How Does Var’s TDZ Differ from Let and Const Variables?** 102 | 103 | The main difference between the temporal dead zone of a `var`, `let`, and `const` variable is when their TDZ ends. 104 | 105 | For instance, consider this code: 106 | 107 | ```js 108 | { 109 | // bestFood’s TDZ starts and ends here 110 | console.log(bestFood); // returns undefined because bestFood’s TDZ does not exist here 111 | var bestFood = "Vegetable Fried Rice"; // bestFood’s TDZ does not exist here 112 | console.log(bestFood); // returns "Vegetable Fried Rice" because bestFood’s TDZ does not exist here 113 | // bestFood’s TDZ does not exist here 114 | // bestFood’s TDZ does not exist here 115 | } 116 | ``` 117 | 118 | - In parsing we do scope resolution, printing happens in execution phase. 119 | 120 | - Difference between `let` and `var` 121 | - The keywords `let` and `var` both declare new variables in JavaScript. The difference between `let` and `var` is in the scope of the variables they create: 122 | - Variables declared by `let` are only available inside the block where they’re defined. 123 | - Variables declared by `var` are available throughout the function in which they’re declared. 124 | 125 | Consider the difference between these two JavaScript functions: 126 | 127 | ```javascript 128 | function varScoping() { 129 | var x = 1; 130 | 131 | if (true) { 132 | var x = 2; 133 | console.log(x); // will print 2 134 | } 135 | 136 | console.log(x); // will print 2 137 | } 138 | 139 | function letScoping() { 140 | let x = 1; 141 | 142 | if (true) { 143 | let x = 2; 144 | console.log(x); // will print 2 145 | } 146 | 147 | console.log(x); // will print 1 148 | } 149 | ``` 150 | 151 | In `varScoping()`, one `x` variable is used throughout the function, even though an `x` variable is declared in two different places with different values. 152 | 153 | In `letScoping()`, two distinct `x` variables are used – one appears in the main function body and another in the `if` block. 154 | 155 | - rule of thumb 156 | - var - function scope 157 | - let - block scope 158 | 159 | --- 160 | 161 | **Var** 162 | 163 | - The var in JavaScript is used to store information it can take any value for example **integer**, **float**, or **string**. We call it a declaration of a variable when the var is created. The value stored in var is empty after the declaration. When we store any value in var it is called initializing the value for var in JavaScript. 164 | - The var has a global scope which means that even if it is declared in a block the variable can be accessed outside the block too. 165 | - As we have already seen that var is global scoped which means we can declare var anywhere in the code not necessarily on the top. Using the variable before it is declared is called hoisting. 166 | 167 | **var_in_block.js** 168 | ```js 169 | function fun() { 170 | var i = 5; 171 | while(i < 10) { 172 | var x = i; 173 | i++; 174 | } 175 | console.log(x); 176 | } 177 | fun(); 178 | 179 | let i = 1; 180 | console.log(y); // undefined here 181 | while(i < 5) { 182 | var y = 10; 183 | i++; 184 | } 185 | console.log(y); // 10 186 | // redeclaration is not allowed with let, but it is allowed with var 187 | // let x = 9; 188 | // let x = 10; 189 | ``` 190 | 191 | - `var x` & `var y` will avoid the while loop and it will get the outside enclosing scope whether it's function scope in case if first while loop (above example) or global scope (2nd while loop). 192 | 193 | **usecasevar.js** 194 | ```js 195 | function fun(x) { 196 | let i; // var i 197 | if(x %2 == 0) { 198 | i = 0; 199 | } else { 200 | i = 1; 201 | } 202 | } 203 | 204 | function gun(x) { 205 | if(x %2 == 0) { 206 | var i = 0; 207 | } else { 208 | var i = 1; 209 | } 210 | console.log(i); 211 | } 212 | 213 | gun(10); // 0 214 | ``` 215 | 216 | - gun() is aclean implementation of fun() 217 | 218 | **usecaselet.js** 219 | ```js 220 | function fun() { 221 | for(let i = 0; i < 10; i++) { 222 | // do something 223 | } 224 | console.log(i); 225 | } 226 | 227 | function process(x, y) { 228 | if(x > y) { 229 | // var temp = x; 230 | let temp = x; 231 | x = y; 232 | y = temp; 233 | } 234 | return y - x; 235 | } 236 | 237 | fun(); 238 | ``` 239 | 240 | - If a variable is not going to be used outside a block then just make it `let` instead of `var`. Let's not give the user to use or misuse it. 241 | - There are use cases for both let and var, you need to make the decision. 242 | - var allows redeclaration. 243 | - let does not allows redeclaration. 244 | 245 | --- 246 | 247 | **Const** 248 | 249 | - The const declaration creates block-scoped constants, much like variables declared using the let keyword. 250 | - The value of a const can't be changed through reassignment (i.e. by using the assignment operator), and it can't be redeclared (i.e. through a variable declaration). 251 | - However, if a constant is an object or array, its properties or items can be updated or removed. 252 | **Properties of Const** 253 | - Cannot be reassigned. 254 | - It’s Block Scope 255 | - It can be assigned to the variable on the declaration line. 256 | - It’s a Primitive value. 257 | - The property of a const object can be changed but it cannot be changed to a reference to the new object 258 | - The values inside the const array can be changed, it can add new items to const arrays but it cannot reference a new array. 259 | - Re-declaring of a const variable inside different block scopes is allowed. 260 | - Cannot be Hoisted. 261 | - Creates only read-only references to value. 262 | 263 | ```js 264 | const x = 10 265 | x = 9 // this will throw error 266 | ``` 267 | 268 | ```js 269 | const obj = {x: 10}; 270 | obj.y = 9 // this is fine - adding a new property to the object. 271 | 272 | obj = {} // this will throw an error 273 | ``` 274 | 275 | - `constant` stops reassignment, it does not stop updates to an object or an array. 276 | - `const { bar } = foo;` This declaration creates a constant whose scope can be either global 4r local to the block in which is declared. 277 | - *Task* - Does the Temporal dead zone exist for `const` ? 278 | - `const y; // This is not allowed` - You cannot have uninitialized `const` 279 | 280 | ```js 281 | const x = 10; 282 | 283 | x.val = 0; 284 | 285 | console.log(x) // 10 286 | ``` 287 | - momentarily it will be treated as an object. 288 | - Concept of Boxing / Auto Boxing / Unboxing. 289 | - The conversion of primitive data types to object data types, i.e., boxing and it's vice-versa, known as unboxing. 290 | - In JavaScript and other languages which are based on object-oriented programming, primitive values don't have any properties or methods. If you want to use them, you need to use a wrapper to convert them into object data types. 291 | - Boxing and unboxing are important and regularly used practices. But in different languages or different implementations, the wrapper can consume more memory and take more time to run the code than primitive types. But, if we talk about higher-level data structures, the wrappers are very useful. That also increases flexibility in your code. 292 | - It is preferred to use boxing implicitly because browser engines are optimized. 293 | - AutoBoxing 294 | - Boxing is the process in which a primitive value is wrapped in an Object. When a primitive type is treated as an object, e.g., calling the toUpperCase() function, JavaScript would automatically wrap the primitive type into the corresponding object type. This new object type is then linked to the related built-in <.prototype>, so you can use prototype methods on primitive types. 295 | - Manual Boxing 296 | - AutoBoxing is quite easy to implement, but it has some issues too. It's not usually a good idea to directly use a boxed object wrapper because sometimes that generates results that are not expected at all. 297 | - Unboxing 298 | - Unboxing is converting the reference or object types to basic or primitive data types. It is the opposite of boxing or packing. 299 | - One of the easiest ways to convert the object wrapper to the respective primitive data type is to use the valueOf() method. 300 | 301 | **Note** - Whenever new scope comes, either a block scope or function scope and in that you have a formal declaration then that formal declaration will be prioritized. 302 | 303 | --- 304 | 305 | ### Function Expression 306 | 307 | **What are JavaScript functions?** 308 | 309 | Functions are essential building blocks in JavaScript, they are packed with logic for performing tasks. A function can be likened to a procedure that performs a task or calculates a value. However, for this procedure to be considered as a function, it needs to take some input and return an output. 310 | 311 | Refer this [Different Ways to Declare Functions - Beginner JavaScript - Wes Bos](https://wesbos.com/javascript/02-functions/different-ways-to-declare-functions) 312 | 313 | **different ways a function can be declared in JavaScript:** 314 | 315 | - Function Expression 316 | - A function can be declared using a function expression. It is declared quite differently from the general syntax because it uses a variable to denote the name of the function. This variable comes before the keyword `function`. 317 | - Anonymous Functions 318 | - Anonymous function declaration allows function names to appear hidden in the declaration itself. In the general function declaration syntax, the function name is attached to the function keyword, but an anonymous function is declared using only the function keyword and a parenthesis. 319 | - Immediately Invoked Function Expression 320 | - IIFE are functions that can be stated as expressions or normal declarations and use the anonymous property of the function expression to execute its code. If you want to execute a function immediately after the declaration, use IIFE. This is executed by wrapping the anonymous function in parentheses and ending it with a semicolon: 321 | - Constructor Functions 322 | - Getter Functions 323 | - Hoisting 324 | - Arrow Functions 325 | - This is a feature available in the ES6 version of JavaScript and as such has not stayed in the space for as long as the other features in the function declaration. It is generally a cleaner way of creating JavaScript functions and it is similar to the function expression. 326 | 327 | **functionexpression.js** 328 | ```js 329 | function fun() { // function declaration 330 | // some impl 331 | } 332 | 333 | let f = function gun() { // named function expression 334 | // some impl 335 | } 336 | 337 | let a = function() { // anonymous function expression 338 | // okk some more impl 339 | } 340 | 341 | (function x() { 342 | // can you stop it ? 343 | }) // function expression 344 | 345 | (function (){ 346 | // i am done 347 | }) 348 | 349 | let y = () => { // Arrow function 350 | 351 | } 352 | ``` 353 | 354 | - There are key differences in all of the above. 355 | - What is function declaration in Javascript? 356 | - starts with `function` 357 | - What id named function function expression? 358 | - starts with `let` 359 | 360 | **Function Expression** 361 | ```js 362 | let x = function () { 363 | console.log('HI'); 364 | } 365 | console.log(x); 366 | x(); 367 | ``` 368 | 369 | - What is an IFFE? 370 | - Immediately Invoked Function Expression 371 | 372 | **Example of IFFE** 373 | ```js 374 | (function x(y) { 375 | console.log("hi", y); 376 | })("Sanket"); 377 | ``` 378 | 379 | **Scope of Function Expression.js** 380 | ```js 381 | const f = function fun() { 382 | console.log("How much fun????"); 383 | } 384 | 385 | console.log(f()); // will give undefined. 386 | // fun(); 387 | ``` 388 | - function `fun` is available only via `f` 389 | 390 | **Function Expressions are of two types** 391 | - named function expression 392 | - anonymous function expression 393 | 394 | **Use Case of Named Function Expression** 395 | 396 | *usecaseofnamedfunctionexpression.js* 397 | ```js 398 | function fun(fn) { 399 | console.log("Welcome to fun"); 400 | fn(); 401 | } 402 | 403 | fun(function () { 404 | console.log("Wow so much fun"); 405 | console.trace(); 406 | }); 407 | 408 | 409 | // for recursive cases named function expression are also helpful 410 | ``` 411 | 412 | - readability of code increases with named function expression. 413 | - importance of writing good function names. 414 | - for recursive cases named function expression are also helpful 415 | - `console. trace()` 416 | - anonymous function are hard to debug since the name of the function is not there in the logs. 417 | - We should use named function expression instead of anonymous function expression. 418 | - arguments.callee, this recursion related regarding in anonymous functions - Read in mozilla docs. 419 | --- 420 | **Use Case of IFFE** 421 | - In order to avoid the naming collusions we can use `IFFEs` 422 | 423 | ```js 424 | function x() { 425 | console.log("Wow"); 426 | } 427 | // 428 | (function x(y) { 429 | console.log("hi", y); 430 | })("Sanket"); 431 | // 432 | x(); 433 | 434 | function f() { 435 | return 1; 436 | 437 | } 438 | 439 | function g() { 440 | return 2; 441 | } 442 | 443 | var i = 10; 444 | 445 | // if(i%2 == 0) { 446 | // var res = f(); 447 | // } else { 448 | // var res = g(); 449 | // } 450 | 451 | var res = (function evaluate(i) { 452 | if(i%2 == 0) return f(); 453 | else return g(); 454 | })(i); 455 | console.log(res); 456 | ``` 457 | 458 | --- 459 | 460 | **Tips** 461 | 462 | - **Don't worry about the framework, worry about the Language** 463 | - **Master Binary Search, Graphs and Dynamic programming.** 464 | 465 | --- 466 | 467 | ## Extra Resources 468 | - [How JavaScript Blocks work 🧱 - DEV Community 👩‍💻👨‍💻](https://dev.to/js_bits_bill/how-javascript-blocks-work-js-bits-aha) 469 | - [Temporal Dead Zone (TDZ) and Hoisting in JavaScript – Explained with Examples](https://www.freecodecamp.org/news/javascript-temporal-dead-zone-and-hoisting-explained/) 470 | - [Difference between \`let\` and \`var\` in JavaScript | Sentry](https://sentry.io/answers/difference-between-let-and-var-in-javascript/) 471 | - [ecmascript 6 - What is the use case for var in ES6? - Stack Overflow](https://stackoverflow.com/questions/31836796/what-is-the-use-case-for-var-in-es6) 472 | - [3 reasons to use 'var' in JavaScript - DEV Community 👩‍💻👨‍💻](https://dev.to/paritho/3-reasons-to-use-var-in-javascript-1hoe) 473 | - [Site Unreachable](https://www.freecodecamp.org/news/understanding-let-const-and-var-keywords/) 474 | - [Different Ways to Declare Functions - Beginner JavaScript - Wes Bos](https://wesbos.com/javascript/02-functions/different-ways-to-declare-functions) 475 | -------------------------------------------------------------------------------- /JavaScript/Chapter 03 - Scopes and Function Expression/Theory/Is-Javascript-Compiled_-Lexical-Scoping.md: -------------------------------------------------------------------------------- 1 | ## Is Javascript Compiled? I Lexical Scoping 2 | - What is a Scope? 3 | - represents visibility → of variables and functions 4 | - scopes tell you where a thing is visible 5 | - Everything (variables & functions) inside your code will used in one of the following two way 6 | - Either it will getting some value assigned to it 7 | - Or some value will be retrieved from it. 8 | - Do you think JavaScript is complied or interpreted? 9 | - Every javascript code is executed in two phases 10 | - Parsing Phase 11 | - Scope resolution 12 | - Execution Phase 13 | - In Javascript, there are three types of scopes. 14 | - Global 15 | - function 16 | - block 17 | - Scope - Refer MDN 18 | - var 19 | - The `var` statement declares a function-scoped or globally-scoped variable, optionally initializing it to a value. 20 | - var declarations, wherever they occur, are processed before any Code is executed. This is called hoisting and is discussed further below. 21 | - let 22 | - The let declaration declares block-scoped local variable, optionally initializing it to a value. 23 | - Parsing 24 | - every time we see formal declaration we think about the scope in parsing phase. 25 | 26 | 27 | - **Lexical Scoping I Auto Global | Function Expressions** 28 | 29 | ```javascript 30 | "use strict"; 31 | var teacher = "Sanket"; 32 | function fun() { 33 | var teacher = "Pulkit"; 34 | // content = "JS"; 35 | console.log(teacher); 36 | // console.log(content); 37 | } 38 | function gun() { 39 | var student = "Sarthak"; 40 | console.log(student); 41 | } 42 | fun(); 43 | gun(); 44 | console.log(teacher); 45 | // console.log(content); 46 | 47 | const o = { p: 1, p: 2 }; 48 | ``` 49 | -------------------------------------------------------------------------------- /JavaScript/Chapter 03 - Scopes and Function Expression/Theory/Lexical-Scoping-Auto-Global.md: -------------------------------------------------------------------------------- 1 | ## Lexical Scoping I Auto Global | 2 | 3 | ```javascript 4 | "use strict"; 5 | var teacher = "Sanket"; 6 | function fun() { 7 | var teacher = "Pulkit"; 8 | // content = "JS"; 9 | console.log(teacher); 10 | // console.log(content); 11 | } 12 | function gun() { 13 | var student = "Sarthak"; 14 | console.log(student); 15 | } 16 | fun(); 17 | gun(); 18 | console.log(teacher); 19 | // console.log(content); 20 | 21 | const o = { p: 1, p: 2 }; 22 | ``` 23 | - auto globals 24 | - You can execute the code in two modes 25 | - strict mode 26 | - sloppy mode 27 | - What is strict mode? 28 | - JavaScript's strict mode a is a way to opt in to a restricted variant of JavaScript, thereby implicitly opting-out of "sloppy mode". 29 | - Strict mode makes several changes to normal JavaScript semantics: 30 | - 1. Eliminates some JavaScript silent errors by changing them to throw errors. 31 | - 2. 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. 32 | - 3. Prohibits some syntax likely to be defined in future versions of ECMAScript. 33 | - to invoke strict mode ⇒ use strict for a whole file or a function 34 | - Assigning to undeclared variables 35 | - Strict mode makes it impossible to accidentally create global variables. In sloppy mode, mistyping a variable in an assignment creates a new property on the global object and continues to "work". Assignments which would accidentally create global variables throw an error in strict mode: 36 | - strict mode stops the creation of auto globals 37 | - auto global - can be a huge problem for production level codebases. 38 | - strict mode can be useful for some performance. - Design Decision 39 | - _> Refer - strict mode documentation page_ 40 | - Interview 41 | - asked language specific things 42 | - There is no syntactical error 43 | - there is no lo function here. 44 | - This fails in execution 45 | - console.log("hi"); 46 | - console..log("hello"); 47 | - console.log("bye"); 48 | - There is syntactical error in the above code. 49 | - dot dot doesn't exist error 50 | - This fails in execution 51 | - Parse Tree 52 | - console.log(10.. toString()); works fine 53 | - console.log(5..toString(2)); 54 | - from number to string 55 | - does the boxing here (primitive to non primitive) 56 | - Why does 10..toString() work, but 10.toString() does not? [stackoverflow] 57 | - Boxing 58 | - The lexer (aka "tokenizer") when reading a new token, and upon first finding digit, will keep consuming characters (i.e. digits or one dot) until it sees a character that is not part of a legal number. 59 | - Parse tree - compiler design 60 | - Nested Scope 61 | - when you're calling the variable inside a function it will try to look outside. 62 | - mazurov.github.io/eslevels-demo/ to visualize scopes 63 | - Lexical vs Dynamic Scoping 64 | - Javascript uses lexical scoping -------------------------------------------------------------------------------- /JavaScript/Chapter 04 - Introduction To Callbacks/Code/callbackdemo2.js: -------------------------------------------------------------------------------- 1 | function fun(x, fn) { 2 | for(let i = 0; i < x; i++) { 3 | console.log(x); 4 | } 5 | 6 | fn(x*x) ; 7 | } 8 | 9 | fun(10, function exec(num) { 10 | console.log(num); 11 | }); // calling fun -------------------------------------------------------------------------------- /JavaScript/Chapter 04 - Introduction To Callbacks/Code/callbacks.js: -------------------------------------------------------------------------------- 1 | /** 2 | * fun -> HOF ? -> it takes fn (which is a function) as argument 3 | * 4 | * x -> number 5 | * fn -> function 6 | */ 7 | 8 | function fun(x, fn) { 9 | for(let i = 0; i < x; i++) { 10 | console.log(i); 11 | } 12 | 13 | fn(); 14 | } 15 | 16 | fun(10, function exec() { // callback 17 | console.log("I am executed also"); 18 | }); -------------------------------------------------------------------------------- /JavaScript/Chapter 04 - Introduction To Callbacks/Code/callbacksdemo.js: -------------------------------------------------------------------------------- 1 | setTimeout(function exec() { 2 | console.log("Running after sometime") 3 | } , 4000); 4 | 5 | 6 | 7 | nameofthefunction() -------------------------------------------------------------------------------- /JavaScript/Chapter 04 - Introduction To Callbacks/Code/hof.js: -------------------------------------------------------------------------------- 1 | // higher order function -> there are functions which take another function as arguments 2 | // these are called higher order functions 3 | 4 | function f(x, fn) { 5 | /** 6 | * x -> number 7 | * fn -> function 8 | */ 9 | console.log(x); 10 | console.log(fn); 11 | fn(); 12 | } 13 | 14 | 15 | f(10, function exec() { 16 | console.log("I am an expression passed to a HOF"); 17 | }); 18 | 19 | let arr = [1,10,9,100,1000,11,12,13,14,2,3]; // unsorted array 20 | 21 | arr.sort(); // it sorts the given array // [expectation] -> this might arrange elements in inc order 22 | // default implementation of arr.sort() is going to sort my array in lexicographical order 23 | /** 24 | * 0 -> A 25 | * 1 -> B 26 | * 2 -> C 27 | * 3 -> D 28 | * 4 -> E 29 | * 5 -> F 30 | * 6 -> G 31 | * 7 -> H 32 | * 8 -> I 33 | * 9 -> J 34 | * .... 35 | * [B, BA, J, BAA, BAAA, BB, BC, BD, BE, C, D] // if we arrange it according to dictionary 36 | * [B, BA, BAA, BAAA, BB, BC, BD .....] 37 | */ 38 | console.log(arr); 39 | 40 | let b = [1,10,9,100,1000,11,12,13,14,2,3]; 41 | 42 | // sort b in increasing order 43 | 44 | b.sort(function cmp(a, b) { 45 | // if a < b -> a - b will be negative -> if cmp function gives negative then a is placed before b (a b -> a - b will be positive -> if cmp function gives positive then b is placed before a (a>b) 47 | return a < b; 48 | }); // sort is a HOF ,, the sort function takes a comparator function as argument 49 | 50 | 51 | console.log(b); 52 | 53 | // B 54 | -------------------------------------------------------------------------------- /JavaScript/Chapter 04 - Introduction To Callbacks/Code/problemswithcallbacks.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 1. Inversion of control (Promises can resolve this issue, will discuss it later) 3 | * 2. Callback hell -> readability problem 4 | */ 5 | 6 | 7 | // let arr = [1,10,1000,9,2,3,11]; 8 | 9 | // arr.sort(function cmp(a, b) { 10 | // return a - b; 11 | // }) 12 | 13 | // console.log(arr); 14 | 15 | 16 | function doTask(fn, x){ 17 | // wholw implementation is done by team A 18 | 19 | // fn(x*x); // calling my callback with square of x 20 | // fn(x*x); 21 | } // team A 22 | 23 | // here team b tries to use it 24 | doTask(function exec(num) { // due to callbacks, I am passing control of how exec should be called to doTask 25 | // this is inversion of control 26 | console.log("Woah num is", num); 27 | }, 9); -------------------------------------------------------------------------------- /JavaScript/Chapter 04 - Introduction To Callbacks/Theory/Callbacks-IVC.md: -------------------------------------------------------------------------------- 1 | ## Callbacks | Inversion of control 2 | 3 | ### Higher Order Functions 4 | 5 | A Higher-Order Function is a regular function that takes one or more functions as arguments and/or returns a function as a value from it. 6 | 7 | - higher order function - there are functions which take another function as arguments 8 | - these are called higher order functions 9 | 10 | ```js 11 | function f(x, fn) { 12 | /** 13 | * x -> number 14 | * fn -> function 15 | */ 16 | console.log(x); 17 | console.log(fn); 18 | fn(); 19 | } 20 | 21 | 22 | f(10, function exec() { 23 | console.log("I am an expression passed to a HOF"); 24 | }); 25 | 26 | let arr = [1,10,9,100,1000,11,12,13,14,2,3]; // unsorted array 27 | 28 | arr.sort(); 29 | ``` 30 | 31 | - `arr.sort();` It sorts the given array // [expectation] -> this might arrange elements in inc order 32 | - default implementation of arr.sort() is going to sort my array in lexicographical order 33 | 34 | ```js 35 | /** 36 | * 0 -> A 37 | * 1 -> B 38 | * 2 -> C 39 | * 3 -> D 40 | * 4 -> E 41 | * 5 -> F 42 | * 6 -> G 43 | * 7 -> H 44 | * 8 -> I 45 | * 9 -> J 46 | * .... 47 | * [B, BA, J, BAA, BAAA, BB, BC, BD, BE, C, D] // if we arrange it according to dictionary 48 | * [B, BA, BAA, BAAA, BB, BC, BD .....] 49 | */ 50 | console.log(arr); 51 | ``` 52 | 53 | - JS sort function, is a higher order function. The sort function takes a comparator function as argument 54 | 55 | ```js 56 | let b = [1,10,9,100,1000,11,12,13,14,2,3]; 57 | 58 | // sort b in increasing order 59 | 60 | b.sort(function cmp(a, b) { 61 | // if a < b -> a - b will be negative -> if cmp function gives negative then a is placed before b (a b -> a - b will be positive -> if cmp function gives positive then b is placed before a (a>b) 63 | return a < b; 64 | }); // sort is a HOF ,, the sort function takes a comparator function as argument 65 | 66 | 67 | console.log(b); 68 | ``` 69 | 70 | - What is Lexicographical order? 71 | - lexicographical order is alphabetical order. The other type is numerical ordering. Consider the following values, `1, 10, 2` 72 | - Those values are in lexicographical order. 10 comes after 2 in numerical order, but 10 comes before 2 in "alphabetical" order. 73 | - What are comparator functions? 74 | - A comparator is **a function that takes two arguments x and y and returns a value indicating the relative order in which x and y should be sorted**. 75 | - What is the worst sorting algorithm? 76 | - The universally-acclaimed worst sorting algorithm is [Bogosort](https://en.wikipedia.org/wiki/Bogosort), sometimes called Monkey Sort or Random Sort. Bogosort develops from the idea that, in probability theory, if a certain phenomenon is possible, then [it will eventually happen](https://www.baeldung.com/cs/randomness#the-theoretical-bases-of-randomness). 77 | 78 | ### Callbacks 79 | 80 | ```js 81 | /** 82 | * fun -> HOF ? -> it takes fn (which is a function) as argument 83 | * 84 | * x -> number 85 | * fn -> function 86 | */ 87 | 88 | function fun(x, fn) { 89 | for(let i = 0; i < x; i++) { 90 | console.log(i); 91 | } 92 | 93 | fn(); 94 | } 95 | 96 | fun(10, function exec() { // callback 97 | console.log("I am executed also"); 98 | }); 99 | ``` 100 | 101 | - Higher order functions consume functions as argument and the function that you pass as argument is called as **callback function**. 102 | - What is the biggest problem with the callbacks? 103 | - Generally you will get the answer as "Callback hell" but 104 | - "You can improve it with promises" → Bu then there's promise Hell 105 | - You can improve it with async await" → But there's async await Hell 106 | - 'callback hell is not the biggest problem'. It is more or less the readability problem. 107 | - There's bigger problem with callbacks, is **Inversion Control**. 108 | - Refer → [callbackhell.com](callbackhell.com) 109 | 110 | ### What is Inversion of Control? in Simple Words. 111 | 112 | Read this for amazing answers. → [ What is Inversion of Control? - Stack Overflow](https://stackoverflow.com/questions/3058/what-is-inversion-of-control) 113 | 114 | What is Inversion of Control? f 115 | 116 | If you follow these simple two steps, you have done inversion of control: 117 | 118 | 1. Separate **what**-to-do part from **when**-to-do part. 119 | 2. Ensure that **when** part knows as _little_ as possible about **what** part; and vice versa. 120 | 121 | There are several techniques possible for each of these steps based on the technology/language you are using for your implementation. 122 | 123 | --- 124 | 125 | The _inversion_ part of the Inversion of Control (IoC) is the confusing thing; because _inversion_ is the relative term. The best way to understand IoC is to forget about that word! 126 | 127 | Inversion of Control is what you get when your program callbacks, e.g. like a gui program. 128 | 129 | For example, in an old school menu, you might have: 130 | 131 | ``` 132 | print "enter your name" 133 | read name 134 | print "enter your address" 135 | read address 136 | etc... 137 | store in database 138 | ``` 139 | 140 | thereby controlling the flow of user interaction. 141 | 142 | In a GUI program or somesuch, instead we say: 143 | 144 | ``` 145 | when the user types in field a, store it in NAME 146 | when the user types in field b, store it in ADDRESS 147 | when the user clicks the save button, call StoreInDatabase 148 | ``` 149 | 150 | So now control is inverted... instead of the computer accepting user input in a fixed order, the user controls the order in which the data is entered, and when the data is saved in the database. 151 | 152 | Basically, **anything** with an event loop, callbacks, or execute triggers falls into this category. 153 | 154 | - Benefits of IoC 155 | - Reduces amount of application code 156 | - Decreases coupling between classes 157 | - Makes the application easier to test and maintain 158 | 159 | *callbackdemo.js* 160 | ```js 161 | /** 162 | * 1. Inversion of control (Promises can resolve this issue, will discuss it later) 163 | * 2. Callback hell -> readability problem 164 | */ 165 | 166 | 167 | // let arr = [1,10,1000,9,2,3,11]; 168 | 169 | // arr.sort(function cmp(a, b) { 170 | // return a - b; 171 | // }) 172 | 173 | // console.log(arr); 174 | 175 | 176 | function doTask(fn, x){ 177 | // whole implementation is done by team A 178 | 179 | // fn(x*x); // calling my callback with square of x 180 | // fn(x*x); 181 | } // team A 182 | 183 | // here team b tries to use it 184 | doTask(function exec(num) { // due to callbacks, I am passing control of how exec should be called to doTask 185 | // this is inversion of control 186 | console.log("Woah num is", num); 187 | }, 9); 188 | ``` 189 | 190 | 191 | -------------------------------------------------------------------------------- /JavaScript/Chapter 04 - Introduction To Callbacks/callbacks_Inversion_of_control_.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/JavaScript/Chapter 04 - Introduction To Callbacks/callbacks_Inversion_of_control_.pdf -------------------------------------------------------------------------------- /JavaScript/Chapter 05 - Async nature/Code/async.js: -------------------------------------------------------------------------------- 1 | console.log("hi"); 2 | setTimeout(function () { console.log("time done"); }); 3 | console.log("by"); -------------------------------------------------------------------------------- /JavaScript/Chapter 05 - Async nature/Code/demo.js: -------------------------------------------------------------------------------- 1 | function timeConsumingByLoop() { 2 | console.log("loop starts"); 3 | for(let i = 0; i < 1000000000; i++) { 4 | // some task 5 | } 6 | console.log("loop ends"); 7 | } 8 | function timeConsumingByRuntimeFeature0() { 9 | console.log("Starting timer"); 10 | setTimeout(function exec() { 11 | console.log("Completed the timer0"); 12 | for(let i = 0; i < 1000000000; i++) { 13 | // some task 14 | } 15 | }, 5000); // 5 sec timer 16 | } 17 | function timeConsumingByRuntimeFeature1() { 18 | console.log("Starting timer"); 19 | setTimeout(function exec() { 20 | console.log("Completed the timer1"); 21 | // while(true) {} 22 | }, 200); // 0 s timer 23 | } 24 | function timeConsumingByRuntimeFeature2() { 25 | console.log("Starting timer"); 26 | setTimeout(function exec() { 27 | console.log("Completed the timer2"); 28 | }, 200); // 200 ms timer 29 | } 30 | 31 | console.log("Hi"); 32 | timeConsumingByLoop(); 33 | timeConsumingByRuntimeFeature0(); 34 | timeConsumingByRuntimeFeature1(); 35 | timeConsumingByRuntimeFeature2(); 36 | timeConsumingByLoop(); 37 | console.log("By"); -------------------------------------------------------------------------------- /JavaScript/Chapter 05 - Async nature/Code/sync.js: -------------------------------------------------------------------------------- 1 | console.log("Hi we are starting"); 2 | 3 | for(let i = 0; i < 10000000000; i++) { 4 | // some task 5 | } 6 | 7 | console.log("Done"); -------------------------------------------------------------------------------- /JavaScript/Chapter 05 - Async nature/How_runtime_helps_in_async_nature_of_JS.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/JavaScript/Chapter 05 - Async nature/How_runtime_helps_in_async_nature_of_JS.pdf -------------------------------------------------------------------------------- /JavaScript/Chapter 05 - Async nature/Theory/Async-Behaviour-with-Callbacks.md: -------------------------------------------------------------------------------- 1 | ## Async Behaviour with Callbacks 2 | 3 | - Interview question to see, if you know the basics of JavaScript. 4 | 5 | ```js 6 | console.log("Hello, World!"); 7 | setTimeout(function exec() { 8 | console.log("Timer done"); 9 | }, 0); 10 | console.log("end"); 11 | 12 | // Hello, World! 13 | // end 14 | // Timer done 15 | ``` 16 | 17 | - Considering, `console.log()` works as sync - we'll have o/p as above. Otherwise it will be treated as async feature. 18 | - Any async code cannot hamper the sync code. 19 | 20 | ```js 21 | console.log("Hello, World!"); 22 | setTimeout(function exec() { 23 | console.log("Timer done"); 24 | }, 0); 25 | for(let i=0;i<100000000; i++) { 26 | // some task 27 | } 28 | console.log("end"); 29 | 30 | // Hello, World! 31 | // end 32 | // Timer done 33 | ``` 34 | 35 | - `console.log()` 36 | - How `console.log()` works is largely dependent on the runtime. 37 | - It is not a core JS feature. 38 | - How does `NodeJS` handles `console.log()` 39 | - Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to `printf(3)` (the arguments are all passed to `utill.format())`). 40 | - Implementation of `console.log()` 41 | - [node-v0.x-archive/console.js at master · nodejs/node-v0.x-archive · GitHub](https://github.com/nodejs/node-v0.x-archive/blob/master/lib/console.js) 42 | - `process.stdout.fd` 43 | - process. stdout and process. stderr differ from other Node.js streams in important ways: 44 | - They are used internally by `console.log()` and `console.error()`, respectively. 45 | - Writes may be synchronous depending on what the stream is connected to and whether the system is Windows or POSIX: 46 | - Files: synchronous on Windows and POSIX 47 | - TTYs (Terminals): asynchronous on Windows, synchronous on POSIX 48 | • Pipes (and sockets): synchronous on Windows, asynchronous on POSIX 49 | Warning: Synchronous writes block the event loop until the write has completed. 50 | Read - [Process | Node.js v19.6.0 Documentation](https://nodejs.org/api/process.html#processstdout) 51 | Read - [Timers in Node.js | Node.js](https://nodejs.org/en/docs/guides/timers-in-node/) 52 | - What are Streams? 53 | - Streams are one of the fundamental concepts that power Node.js applications. They are data-handling method and are used to read or write input into output sequentially. 54 | - What makes streams unique, is that instead of a program reading a file into memory **all at once** like in the traditional way, streams read chunks of data piece by piece, processing its content without keeping it all in memory. 55 | - Read - [Understanding Streams in Node.js - NodeSource](https://nodesource.com/blog/understanding-streams-in-nodejs/) 56 | - What is POSIX? 57 | - POSIX (Portable Operating System Interface) is a set of standard operating system [interfaces](https://www.techtarget.com/whatis/definition/interface) based on the [Unix](https://www.techtarget.com/searchdatacenter/definition/Unix) operating system. The most recent POSIX specifications -- IEEE Std 1003.1-2017 -- defines a standard interface and environment that can be used by an operating system ([OS](https://www.techtarget.com/whatis/definition/operating-system-OS)) to provide access to POSIX-compliant applications. The standard also defines a command interpreter ([shell](https://www.techtarget.com/searchdatacenter/definition/shell)) and common [utility](https://www.techtarget.com/whatis/definition/utility) programs. POSIX supports application [portability](https://www.techtarget.com/searchstorage/definition/portability) at the [source code](https://www.techtarget.com/searchapparchitecture/definition/source-code) level so applications can be built to run on any POSIX-compliant OS. 58 | - What is Streaming Data? 59 | - Streaming data is data that is continuously generated by different sources. Such data should be processed incrementally using stream processing techniques without having access to all of the data. 60 | - What is a TTY Terminal? 61 | - [Difference Between a Terminal, Shell, TTY, and Console | Baeldung on Linux](https://www.baeldung.com/linux/terminal-shell-tty-vs-console) 62 | 63 | ```js 64 | console.log("Hello, World!"); 65 | setTimeout(function exec() { 66 | console.log("Timer done"); 67 | setTimeout(function exec() { 68 | console.log("woah another one"); 69 | }, 10); 70 | }, 0); 71 | 72 | for(let i=0;i<100000000; i++) { 73 | // some task 74 | } 75 | console.log("end"); 76 | 77 | // Hello, World! 78 | // end 79 | // Timer done 80 | // another one 81 | ``` 82 | 83 | - `setInterval()` 84 | - returns a number in chrome 85 | - returns an object in node runtime 86 | - `clearInterval()` 87 | - Function with same name might behave differently in different runtimes. -------------------------------------------------------------------------------- /JavaScript/Chapter 05 - Async nature/Theory/How-runtime-helps-in-async-nature-of-JS.md: -------------------------------------------------------------------------------- 1 | 2 | ![js-runtime](https://github.com/xoraus/Backend-Specialization/blob/main/attachments/js.png) 3 | 4 | - JavaScript is sync in nature. 5 | - JavaScript is single threaded. 6 | 7 | ```js 8 | console.log("Hi we are starting"); 9 | 10 | for(let i = 0; i < 10000000000; i++) { 11 | // some task 12 | } 13 | 14 | console.log("Done"); 15 | ``` 16 | 17 | - What is the meaning of Asynchronous programming? 18 | - Asynchronous programming is a technique that enables your program to start a potentially long-running task and still be able to be responsive to other events while that task runs, rather than having to wait until that task has finished. Once that task has finished, your program is presented with the result. 19 | - [**Synchronous**](https://stackoverflow.com/questions/10570246/what-is-non-blocking-or-asynchronous-i-o-in-node-js) (or sync) execution usually refers to code executing in sequence. In sync programming, the program is executed line by line, one line at a time. Each time a function is called, the program execution waits until that function returns before continuing to the next line of code. 20 | - **Asynchronous** (or async) execution refers to execution that doesn’t run in the sequence it appears in the code. In async programming the program doesn’t wait for the task to complete and can move on to the next task. 21 | 22 | ```js 23 | console.log("hi"); 24 | setTimeout(function () { console.log("time done"); }); 25 | console.log("by"); 26 | 27 | // hi 28 | // by 29 | // time done 30 | ``` 31 | 32 | - JS is not that powerful, as people claim it to be. 33 | - A runtime is required to run JS in browser. 34 | - JS + Runtime = Hulk of Programming World. 35 | - JS in sync in nature for the piece of code which is native to JS. 36 | - Runtime provides a lot of functionalities to JS. 37 | - What is Runtime? 38 | - A runtime is the environment in which a programming language executes. The runtime system facilitates storing functions, variables, and managing memory by using data structures such as queues, heaps and stacks (more on this later). 39 | - The JavaScript runtime environment provides access to built-in libraries and objects that are available to a program so that it can interact with the outside world and make the code work. 40 | - What is a Call Stack? 41 | - When you write a program, you may compose it of multiple functions. The call stack keeps track all function calls during throughout the life time of the program and execute them in the reverse order that they are called. 42 | - Hence why crashing a program with never ending recursive function calls is said to be a stack/buffer overflow. The stack had so many function calls that it ran out of memory space. 43 | - What are Threads? 44 | - In an OS you can run a program which can be comprised of processes. A process can then be comprised of multiple threads. A thread is the smallest unit of computation that can be individually scheduled. 45 | - What is Multithreading? 46 | - Computers with multiple cores can process multiple threads at the same time. Some programming languages support multithreading by allowing your program to spawn child threads to perform a task then return the result to the parent. Such runtime would provide multiple call stacks. Each call stack is delegated to a thread. 47 | - What makes JavaScript's runtime so special? 48 | - By design the JavaScript interpreter is single-threaded, this is a good thing because it makes it easier to implement browsers for all kinds of devices, consoles, watches fridges etc. 49 | - But then you may wonder how do web apps work if the interpreter can only do one thing at a time? Well even though JavaScript is single threaded, it executes tasks in a concurrent fashion. 50 | - Simply put, concurrency is breaking up tasks and switching between so quickly that they all appear to progress at the same time. Contrast this with parallelism which is performing tasks simultaneously. 51 | - In the context of a browser this is comprised of the following elements: 52 | - The JavaScript engine (which in turn is made up of the heap and the call stack) 53 | - Web APIs 54 | - The callback queue 55 | - The event loop 56 | - The purpose of the JavaScript engine is to translate source code that developers write into machine code that allows a computer to perform specific tasks. 57 | - Let's focus on the V8 JavaScript engine. 58 | - **The heap** 59 | - The heap, also called the ‘memory heap’, is a section of unstructured memory that is used for the allocation of objects and variables. 60 | - **The call stack** 61 | - The call stack is a data structure that keeps track of where we are in the program and runs in a last-in, first-out way. Each entry in the stack is called a stack frame. This means that the frame at the top of the stack is the one the engine is focused on, and it will not move on to the next function unless the function above it has been removed from the stack. 62 | - As the JS engine steps into a function, it is pushed onto the stack. When a function returns a value or gets sent to the Web APIs, it is popped off the stack. If a function doesn’t explicitly return a value then the engine will return undefined and also pop the function off the stack. This is what is meant by the term “JavaScript runs synchronously”; it is single-threaded, so can only do one thing at a time. 63 | - **Web APIs** 64 | - The Web APIs are not a part of the JavaScript engine, but they are part of the runtime environment provided by the browser. There are a large number of APIs available in modern browsers that allow us to a wide variety of things. 65 | - **The callback queue** 66 | - The callback queue stores the callback functions sent from the Web APIs in the order in which they were added. This queue is a data structure that runs first in, first out. The queue uses the array push method to add a new callback function to the end of the queue and the array shift method to remove the first item in the queue. 67 | - Callback functions will sit in the queue until the call stack is empty, they are then moved into the stack by the event loop. 68 | - **The event loop** 69 | - The job of the event loop is to constantly monitor the state of the call stack and the callback queue. If the stack is empty it will grab a callback from the callback queue and put it onto the call stack, scheduling it for execution. 70 | - This is why JavaScript often gets described as being able to run asynchronously, even though it is a single-threaded language. JavaScript can only execute one function at a time, so this means it is synchronous, but as we can push callbacks from the Web APIs to the callback queue and in turn, the event loop can constantly add those callback to the call stack, we think of JavaScript as being able to run asynchronously. 71 | 72 | ```js 73 | function timeConsumingByLoop() { 74 | console.log("loop starts"); 75 | for(let i = 0; i < 1000000000; i++) { 76 | // some task 77 | } 78 | console.log("loop ends"); 79 | } 80 | function timeConsumingByRuntimeFeature0() { 81 | console.log("Starting timer"); 82 | setTimeout(function exec() { 83 | console.log("Completed the timer0"); 84 | for(let i = 0; i < 1000000000; i++) { 85 | // some task 86 | } 87 | }, 5000); // 5 sec timer 88 | } 89 | function timeConsumingByRuntimeFeature1() { 90 | console.log("Starting timer"); 91 | setTimeout(function exec() { 92 | console.log("Completed the timer1"); 93 | // while(true) {} 94 | }, 200); // 0 s timer 95 | } 96 | function timeConsumingByRuntimeFeature2() { 97 | console.log("Starting timer"); 98 | setTimeout(function exec() { 99 | console.log("Completed the timer2"); 100 | }, 200); // 200 ms timer 101 | } 102 | console.log("Hi"); 103 | timeConsumingByLoop(); 104 | timeConsumingByRuntimeFeature0(); 105 | timeConsumingByRuntimeFeature1(); 106 | timeConsumingByRuntimeFeature2(); 107 | timeConsumingByLoop(); 108 | console.log("By"); 109 | ``` 110 | 111 | - The code demonstrates the asynchronous nature of the JavaScript runtime. In JavaScript, the `setTimeout` function is an example of an asynchronous function. This means that the function returns immediately and does not wait for the specified time to pass before executing the callback function. In this code, the `timeConsumingByRuntimeFeature0`, `timeConsumingByRuntimeFeature1`, and `timeConsumingByRuntimeFeature2` functions set timers using the `setTimeout` function, each with a different waiting time. The function returns immediately, allowing the code to continue executing the `timeConsumingByLoop` function and the next `setTimeout` function without waiting for the timer to finish. Meanwhile, the JavaScript runtime is executing the timers in the background and executing the corresponding callback functions when the timers are finished. In contrast, the `timeConsumingByLoop` function runs synchronously, blocking the rest of the code until it finishes. 112 | - we never pause a sync piece of code. 113 | - The moment runtime's done with the task it gets added to the event queue. 114 | - Event Loop 115 | - Infinite Loop 116 | - It keeps on checking whether the call stack is empty or not & no global code is left. 117 | - Ready to be executed callback functions (coming from the events) 118 | - The job of event loop is to continuously check if an event occurred, like mouse click or keyboard stroke so that it can send that to call stack. Of course, your mouse click will be given higher priority for execution than an image load. 119 | - In a nutshell, the asynchronous implementation in Javascript is done through a call stack, call back queue and Web API and event loop. 120 | 121 | **Summary** 122 | 123 | - The runtime environment is what makes JavaScript code work, and in a browser in consists of the JS engine, a lot of Web APIs, a callback queue and the event loop 124 | - The JS engine translates source code into machine code that allows a computer to perform specific tasks at the hardware level 125 | - Web APIs extend the JS language and push callback functions to the callback queue once actions are complete and data has been received 126 | - The callback queue stores callback functions in order, ready to be executed 127 | - The event loop is constantly monitoring the call stack and the callback queue; if the call stack is empty it will move the callback function at the front of the queue to the call stack, scheduling it for execution 128 | 129 | **References** 130 | - [What is the JavaScript runtime? - DEV Community 👩‍💻👨‍💻](https://dev.to/snickdx/what-is-the-javascript-runtime-4n09) 131 | - [Understanding the JavaScript runtime environment | by Gemma Croad | Medium](https://medium.com/@gemma.croad/understanding-the-javascript-runtime-environment-4dd8f52f6fca) 132 | - [What does it mean by Javascript is single threaded language | by Sharjeel Siddique | The Startup | Medium](https://medium.com/swlh/what-does-it-mean-by-javascript-is-single-threaded-language-f4130645d8a9) 133 | -------------------------------------------------------------------------------- /JavaScript/Chapter 06 - Introduction To Promises/Code/createPromiseWithLoop.js: -------------------------------------------------------------------------------- 1 | 2 | // 🔥 Run this code in the browser console section for better output 3 | 4 | function getRandomInt(max) { 5 | return Math.floor(Math.random() * max); 6 | } 7 | 8 | function createPromiseWithLoop() { 9 | return new Promise(function executor(resolve, reject) { 10 | for(let i = 0; i < 1000000 ; i++) {} 11 | let num = getRandomInt(10); 12 | if(num % 2 == 0) { 13 | // if the random number is even, we fulfill the promise 14 | resolve(num); 15 | } 16 | else{ 17 | // otherwise we reject the promise 18 | reject(num); 19 | } 20 | }); 21 | } 22 | 23 | let x = createPromiseWithLoop(); 24 | console.log(x); 25 | 26 | 27 | // output the results ( it can be different in your case) 28 | 29 | // Promise {: 6} 30 | // [[Prototype]]: Promise 31 | // [[PromiseState]]: "fulfilled" 32 | // [[PromiseResult]]: 6 33 | 34 | 35 | // 🔥 Run above code in the browser console section for better output -------------------------------------------------------------------------------- /JavaScript/Chapter 06 - Introduction To Promises/Code/createPromiseWithSetTimeout.js: -------------------------------------------------------------------------------- 1 | 2 | // 🔥 Run this code in the browser console section for better output 3 | 4 | function getRandomInt(max) { 5 | return Math.floor(Math.random() * max); 6 | } 7 | 8 | function createPromiseWithSetTimeout() { 9 | return new Promise(function executor(resolve, reject) { 10 | setTimeout(function () { 11 | let num = getRandomInt(10); 12 | if(num % 2 == 0) { 13 | // if the random number is even, we fulfill the promise 14 | resolve(num); 15 | } 16 | else{ 17 | // otherwise we reject the promise 18 | reject(num); 19 | } 20 | }, 10000); 21 | }); 22 | } 23 | 24 | let x = createPromiseWithSetTimeout(); 25 | console.log(x); 26 | 27 | 28 | // Output the results ( it can be different in your case) 29 | 30 | 31 | // Promise {} // state -> pending 32 | // [[Prototype]]: Promise 33 | // [[PromiseState]]: "fulfilled" 34 | // [[PromiseResult]]: 2 35 | 36 | // but after finishing the setTimeout function 37 | 38 | 39 | // Promise {: 2} // state -> fulfilled 40 | // [[Prototype]]: Promise 41 | // [[PromiseState]]: "fulfilled" 42 | // [[PromiseResult]]: 2 43 | 44 | 45 | // Run above code in the browser console section for better output -------------------------------------------------------------------------------- /JavaScript/Chapter 06 - Introduction To Promises/Code/passingMultipleValues.js: -------------------------------------------------------------------------------- 1 | 2 | // 🔥 Run this code in the browser console section for better output 3 | 4 | function getRandomInt(max) { 5 | return Math.floor(Math.random() * max); 6 | } 7 | 8 | function createPromiseWithSetTimeout() { 9 | return new Promise(function executor(resolve, reject) { 10 | setTimeout(function () { 11 | let num = getRandomInt(10); 12 | if(num % 2 == 0) { 13 | // if the random number is even, we fulfill the promise 14 | resolve(num, 10, 20, 30); // passing multiple values 15 | } 16 | else{ 17 | // otherwise we reject the promise 18 | reject(num); 19 | } 20 | }, 10000); 21 | }); 22 | } 23 | 24 | let x = createPromiseWithSetTimeout(); 25 | console.log(x); 26 | 27 | 28 | // if we pass multiple values in 'resolve' or 'reject' , it will only take the first value 29 | // output will be : num ( whatever in its inside) 30 | 31 | 32 | // 🔥 Run above code in the browser console section for better output -------------------------------------------------------------------------------- /JavaScript/Chapter 06 - Introduction To Promises/Code/returningBeforeResolveOrReject.js: -------------------------------------------------------------------------------- 1 | 2 | // 🔥 Run this code in the browser console section for better output 3 | 4 | function getRandomInt(max) { 5 | return Math.floor(Math.random() * max); 6 | } 7 | 8 | function createPromiseWithSetTimeout() { 9 | return new Promise(function executor(resolve, reject) { 10 | setTimeout(function () { 11 | let num = getRandomInt(10); 12 | if(num % 2 == 0) { 13 | // if the random number is even, we fulfill the promise 14 | console.log("fulfilling"); 15 | return num; 16 | 17 | } 18 | else{ 19 | // otherwise we reject the promise 20 | console.log("rejecting"); 21 | return num; 22 | } 23 | }, 10000); 24 | }); 25 | } 26 | 27 | let x = createPromiseWithSetTimeout(); 28 | console.log(x); 29 | 30 | /** 31 | * REMEMBER : 32 | * 33 | * If we do not call anyone, the promise will stay forever in 'Pending' state. 34 | * 35 | */ 36 | 37 | 38 | // output 39 | 40 | // Promise {} // state -> pending 41 | // [[Prototype]]: Promise 42 | // [[PromiseState]]: "pending" 43 | // [[PromiseResult]]: undefined 44 | 45 | // rejecting 46 | 47 | // Promise {} // state -> pending 48 | // [[Prototype]]: Promise 49 | // [[PromiseState]]: "pending" 50 | // [[PromiseResult]]: undefined 51 | 52 | 53 | 54 | // 🔥 Run above code in the browser console section for better output -------------------------------------------------------------------------------- /JavaScript/Chapter 06 - Introduction To Promises/Introduction_to_promises.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/JavaScript/Chapter 06 - Introduction To Promises/Introduction_to_promises.pdf -------------------------------------------------------------------------------- /JavaScript/Chapter 06 - Introduction To Promises/Theory/intro-to-promises.md: -------------------------------------------------------------------------------- 1 | ## Introduction to Promises 2 | 3 | - 💡 What is Promise? 4 | - Promise object is a placeholder for certain period of time until we receive value from asynchronous operation. 5 | - A container for a future value. 6 | - **A Promise is an object representing the eventual completion or failure of an asynchronous operation.** 7 | 8 | Imagine that you’re a top singer, and fans ask day and night for your upcoming song. 9 | 10 | To get some relief, you promise to send it to them when it’s published. You give your fans a list. They can fill in their email addresses, so that when the song becomes available, all subscribed parties instantly receive it. And even if something goes very wrong, say, a fire in the studio, so that you can’t publish the song, they will still be notified. 11 | 12 | Everyone is happy: you, because the people don’t crowd you anymore, and fans, because they won’t miss the song. 13 | 14 | > **_Benefits of Promises_** 15 | 16 | 1. Improves Code Readability 17 | 2. Better handling of asynchronous operations 18 | 3. Better flow of control definition in asynchronous logic 19 | 4. Better Error Handling 20 | 21 | - Promises increases the readability of code. 22 | - Promises helps us in solving the problem of **Inversion of Control**. 23 | - In JS, Promises are special type of objects that get returned immediately when we call them. 24 | - Promises acts as placeholder for the data as we hope to get back sometime in future 25 | - `x = fetch("http://www.xyz.com")` 26 | - assume fetch is written using promise then, it will immediately return a promise object as a placeholder. 27 | - In these promise objects we can attach the functionality we want to execute once the future task is done. 28 | - once the future task is done, promises will automatically executes attached functionality. 29 | - Promise 30 | - maybe we fulfill the promise 31 | - maybe we don't fulfill the promise. 32 | - How we can create a promise? 33 | - creation of a promise object is sync in nature. 34 | - How can we consume a promise? 35 | - A Promise is an object that is used as a placeholder for the eventual results of a deferred (and possibly asynchronous) computation. 36 | - Any Promise object is in one of three mutually exclusive states: fulfilled, rejected, and pending. 37 | - pending → when we create a new promise object this is the default state. It represents work in progress 38 | - fulfilled → if the operation is completed successfully. 39 | - rejected → if operation was not successful. 40 | - ```new Promise(f)``` 41 | 42 | ```js 43 | let promise = new Promise(function(resolve, reject) { 44 | // inside the function we can write our time consuming task. 45 | }); 46 | ``` 47 | 48 | - `resolve` and `reject` are normal functions. 49 | - Whenever in the implementation of executor callback you call the resolve function, the promise goes to a fullfilled state. 50 | - If you call reject func, it goes to a rejected state and if you don't call anything, promise remains in pending state. 51 | - In pending state the `value` prop of either (resolve or reject)remains undefined. 52 | 53 | ```js 54 | function createPromiseWithTimeout() { 55 | return new Promise(function executor(resolve, reject) { 56 | setTimeout(function() { 57 | let num = getRandomInt(10); 58 | if (num % 2 == 0) { 59 | // if the random number is even we fulfill 60 | resolve(num); 61 | } else { 62 | // if the random number is odd we reject 63 | reject(num); 64 | } 65 | }, 10000); 66 | }); 67 | } 68 | 69 | let y = createPromiseWithTimeout(); 70 | console.log(y); 71 | ``` 72 | 73 | The code defines a function called `createPromiseWithTimeout` that returns a Promise object that resolves or rejects after a specified timeout. 74 | 75 | The Promise object is created using the Promise constructor, which takes an executor function as its argument. The executor function is passed two callback functions, `resolve` and `reject`, which are used to resolve or reject the Promise. 76 | 77 | The executor function starts a timer using the `setTimeout` function, which waits for 10 seconds (specified as the second argument to `setTimeout`) before executing its callback function. The callback function generates a random integer between 0 and 9 using the `getRandomInt` function. If the integer is even, the Promise is fulfilled with the `resolve` function and the random even integer as the argument. If the integer is odd, the Promise is rejected with the `reject` function and the random odd integer as the argument. 78 | 79 | After the Promise is created, the code assigns the result of calling the `createPromiseWithTimeout` function to the variable `y`, and logs the Promise object to the console. 80 | 81 | Note that since the Promise returned by `createPromiseWithTimeout` is asynchronous, the value of `y` logged to the console will be a Promise object, not the resolved value of the Promise. 82 | -------------------------------------------------------------------------------- /JavaScript/Chapter 07 - How to consume a promise- Part-2/Code/consumingPromise.js: -------------------------------------------------------------------------------- 1 | function getRandomInt(max) { 2 | return Math.floor(Math.random() * max); 3 | } 4 | function createPromiseWithTimeout() { 5 | return new Promise(function executor(resolve, reject) { 6 | console.log("Entering the executor callback in the promise constructor"); 7 | setTimeout(function () { 8 | let num = getRandomInt(10); 9 | if(num % 2 == 0) { 10 | // if the random number is even we fullfill 11 | resolve(num); 12 | } else { 13 | // if the random number is odd we reject 14 | reject(num); 15 | } 16 | }, 1000); 17 | console.log("Exitting the executor callback in the promise constructor"); 18 | }); 19 | } 20 | console.log("Starting...."); 21 | const p = createPromiseWithTimeout(); 22 | console.log("We are now waiting for the promise to complete"); 23 | console.log("Currently my promise object is like ... ", p); 24 | console.log("Going to register my 1st set of handlers"); 25 | p 26 | .then( 27 | function fulfillHandler1(value) { 28 | console.log("Inside fulfill handler 1 with value", value); 29 | console.log("Promise after fullfillment is", p); 30 | setTimeout(function t() {console.log("Ended 0s timer")}, 0); 31 | console.log("exitting the full handler 1"); 32 | }, 33 | function rejectionHandler1(value) { 34 | console.log("Inside rejection handler 1 with value", value); 35 | console.log("Promise after rejection is", p); 36 | setTimeout(function t() {console.log("Ended 0s timer")}, 0); 37 | console.log("exitting the reject handler 1"); 38 | } 39 | ); 40 | console.log("Going to register my 2nd set of handlers"); 41 | 42 | p 43 | .then( 44 | function fulfillHandler2(value) { 45 | console.log("Inside fulfill handler 2 with value", value); 46 | console.log("Promise after fullfillment is", p); 47 | }, 48 | function rejectionHandler2(value) { 49 | console.log("Inside rejection handler 2 with value", value); 50 | console.log("Promise after rejection is", p); 51 | 52 | } 53 | ); 54 | 55 | console.log("Ending......"); 56 | setTimeout(function () {console.log("Global timer of 0s")}, 1000); 57 | 58 | 59 | -------------------------------------------------------------------------------- /JavaScript/Chapter 07 - How to consume a promise- Part-2/Code/microtask_demo.js: -------------------------------------------------------------------------------- 1 | function createPromise() { 2 | return new Promise(function exec(resolve, reject) { 3 | console.log("Resolving the promise"); 4 | resolve("Done"); 5 | }); 6 | } 7 | 8 | setTimeout(function process() { 9 | console.log("Timer completed"); 10 | }, 0); 11 | 12 | let p = createPromise(); 13 | p.then(function fulfillHandler1(value) { 14 | console.log("we fulfilled1 with a value", value); 15 | }, function rejectHandler() {}); 16 | p.then(function fulfillHandler2(value) { 17 | console.log("we fulfilled2 with a value", value); 18 | }, function rejectHandler() {}); 19 | p.then(function fulfillHandler3(value) { 20 | console.log("we fulfilled3 with a value", value); 21 | }, function rejectHandler() {}); 22 | 23 | for(let i = 0; i < 10000000000; i++) {} 24 | 25 | console.log("ending"); -------------------------------------------------------------------------------- /JavaScript/Chapter 07 - How to consume a promise- Part-2/Code/microtaskqueuedemo.js: -------------------------------------------------------------------------------- 1 | function createPromise() { 2 | return new Promise(function exec(resolve, reject) { 3 | setTimeout(function () { 4 | console.log("rejecting the promise"); 5 | reject("Done"); 6 | }, 1000); 7 | }); 8 | } 9 | 10 | 11 | let p = createPromise(); 12 | p.then(function fulfillHandler1(n) { 13 | console.log("we fulfilled1 with a value", n); 14 | }, function rejectHandler(value) { 15 | console.log("we reject1 with a value", value); 16 | }); 17 | p.then(function fulfillHandler2(value) { 18 | console.log("we fulfilled2 with a value", value); 19 | }, function rejectHandler(value) { 20 | console.log("we reject2 with a value", value); 21 | }); 22 | 23 | p.then().then().then().then(); 24 | 25 | 26 | for(let i = 0; i < 10000000000; i++) {} 27 | 28 | console.log("ending"); 29 | -------------------------------------------------------------------------------- /JavaScript/Chapter 07 - How to consume a promise- Part-2/How to consume a promise.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/JavaScript/Chapter 07 - How to consume a promise- Part-2/How to consume a promise.pdf -------------------------------------------------------------------------------- /JavaScript/Chapter 07 - How to consume a promise- Part-2/notes.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/JavaScript/Chapter 07 - How to consume a promise- Part-2/notes.pdf -------------------------------------------------------------------------------- /JavaScript/Chapter 08 - Part - 3 Promises practice/Code/demo1.js: -------------------------------------------------------------------------------- 1 | function fetchData(url) { 2 | return new Promise(function (resolve, reject) { 3 | console.log("Started downloading from", url); 4 | setTimeout(function processDownloading() { 5 | let data = "Dummy data"; 6 | resolve(data); 7 | console.log("Download completed"); 8 | }, 7000); 9 | }); 10 | } 11 | 12 | console.log("Start"); 13 | let promiseObj = fetchData("skfbjkdjbfv"); 14 | promiseObj.then(function A(value) { 15 | console.log("value is", value); 16 | }) 17 | console.log("end"); 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /JavaScript/Chapter 08 - Part - 3 Promises practice/Code/demo2.js: -------------------------------------------------------------------------------- 1 | console.log("Start of the file"); 2 | 3 | setTimeout(function timer1() { 4 | console.log("Timer 1 done"); 5 | }, 0); 6 | 7 | for(let i = 0; i < 10000000000; i++) { 8 | // something 9 | } 10 | 11 | let x = Promise.resolve("Sanket's promise"); 12 | x.then(function processPromise(value) { 13 | console.log("Whose promise ? ", value); 14 | }); 15 | 16 | setTimeout(function timer2() { 17 | console.log("Timer 2 done"); 18 | }, 0); 19 | 20 | console.log("End of the file"); 21 | -------------------------------------------------------------------------------- /JavaScript/Chapter 08 - Part - 3 Promises practice/Code/demo3.js: -------------------------------------------------------------------------------- 1 | function blocking_for_loop() { 2 | for(let i = 0; i < 10000000000; i++) { 3 | // something 4 | } 5 | } 6 | console.log("Start of the file"); 7 | setTimeout(function timer1() { 8 | console.log("Timer 1 done"); 9 | }, 0); 10 | blocking_for_loop(); 11 | let x = Promise.resolve("Sanket's promise1"); 12 | x.then(function processPromise(value) { 13 | console.log("Whose promise ? ", value); 14 | blocking_for_loop(); 15 | }); 16 | let y = Promise.resolve("Sanket's promise2"); 17 | y.then(function processPromise(value) { 18 | console.log("Whose promise ? ", value); 19 | setTimeout(function () {console.log("ok done")}, 0); 20 | }); 21 | let z = Promise.resolve("Sanket's promise3"); 22 | z.then(function processPromise(value) { 23 | console.log("Whose promise ? ", value); 24 | }); 25 | setTimeout(function timer2() { 26 | console.log("Timer 2 done"); 27 | }, 0); 28 | console.log("End of the file"); 29 | -------------------------------------------------------------------------------- /JavaScript/Chapter 08 - Part - 3 Promises practice/Code/pain.js: -------------------------------------------------------------------------------- 1 | Promise.resolve("foo") 2 | // 1. Receive "foo", concatenate "bar" to it, and resolve that to the next then 3 | .then( 4 | (string) => 5 | new Promise((resolve, reject) => { 6 | setTimeout(() => { 7 | string += "bar"; 8 | resolve(string); 9 | }, 1); 10 | }), 11 | ) 12 | // 2. receive "foobar", register a callback function to work on that string 13 | // and print it to the console, but not before returning the unworked on 14 | // string to the next then 15 | .then((string) => { 16 | setTimeout(() => { 17 | string += "baz"; 18 | console.log(string); // foobarbaz 19 | }, 1); 20 | return string; 21 | }) 22 | // 3. print helpful messages about how the code in this section will be run 23 | // before the string is actually processed by the mocked asynchronous code in the 24 | // previous then block. 25 | .then((string) => { 26 | console.log( 27 | "Last Then: oops... didn't bother to instantiate and return a promise in the prior then so the sequence may be a bit surprising", 28 | ); 29 | 30 | // Note that `string` will not have the 'baz' bit of it at this point. This 31 | // is because we mocked that to happen asynchronously with a setTimeout function 32 | console.log(string); // foobar 33 | }); 34 | 35 | // Logs, in order: 36 | // Last Then: oops... didn't bother to instantiate and return a promise in the prior then so the sequence may be a bit surprising 37 | // foobar 38 | // foobarbaz -------------------------------------------------------------------------------- /JavaScript/Chapter 08 - Part - 3 Promises practice/Code/promisechainingmdn.js: -------------------------------------------------------------------------------- 1 | Promise.resolve("foo") 2 | .then(function p1(string) { 3 | return new Promise((resolve, reject) => { 4 | setTimeout(() => { 5 | string += "bar"; //foobar 6 | resolve(string); 7 | }, 10000); 8 | }) 9 | } 10 | ) 11 | .then(function p2(string) { 12 | setTimeout(() => { 13 | string += "baz"; 14 | console.log(string); // foobarbaz 15 | }, 1); 16 | return string; // foobar 17 | }) 18 | .then(function p3(string) { 19 | console.log(string); // foobar 20 | }); 21 | -------------------------------------------------------------------------------- /JavaScript/Chapter 08 - Part - 3 Promises practice/Code/promisedownloaddummy.js: -------------------------------------------------------------------------------- 1 | function download(url) { 2 | console.log("started downloading content form ", url); 3 | return new Promise(function exec(res, rej) { 4 | setTimeout(function p() { 5 | console.log("COmpelted downloading data in 5s"); 6 | const content = "ABCDEF"; 7 | res(content); 8 | }, 5000); 9 | }) 10 | } 11 | 12 | x = download("www.xyz.com"); 13 | x 14 | .then( 15 | function fulfillHandler1(value) { 16 | console.log("Content downloaded is1", value); 17 | return "New promise string"; 18 | }, 19 | function rejectHandler1(value) { 20 | console.log("rejected with", value); 21 | } 22 | ) 23 | .then( 24 | function newFullFillHandler(value) { 25 | console.log("value from chained then promsie", value); 26 | } 27 | ) -------------------------------------------------------------------------------- /JavaScript/Chapter 08 - Part - 3 Promises practice/Code/promiseschaineddemo.js: -------------------------------------------------------------------------------- 1 | Promise.resolve("foo") 2 | .then(function fh1(value) { 3 | return Promise.resolve(value+"bar"); 4 | }) 5 | .then(function fh2(value) { 6 | setTimeout(function exec() { 7 | value+="baz"; 8 | console.log(value); 9 | return 10; 10 | }, 1); 11 | // return value; 12 | }) 13 | .then(function fh3(value) { 14 | console.log("from fh3", value); 15 | }) -------------------------------------------------------------------------------- /JavaScript/Chapter 08 - Part - 3 Promises practice/Part 3 - Promises Practice.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/JavaScript/Chapter 08 - Part - 3 Promises practice/Part 3 - Promises Practice.pdf -------------------------------------------------------------------------------- /JavaScript/Chapter 08 - Part - 3 Promises practice/Theory/notes.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/JavaScript/Chapter 08 - Part - 3 Promises practice/Theory/notes.pdf -------------------------------------------------------------------------------- /JavaScript/Chapter 09 - Part - 4 Promises and callbacks practice/Code/callbackImpl.js: -------------------------------------------------------------------------------- 1 | // Tasks: (Don't use promises only use callbacks) 2 | // 1. Write a function to download data from a url 3 | // 2. Write a function to save that downloaded data in a file and return the filename 4 | // 3. Write a function to upload the file written in previous step to a newurl 5 | 6 | function download(url, cb) { 7 | /** 8 | * Downloads content from the given url and passed the 9 | * downloaded content to the given callback cb 10 | */ 11 | console.log("Starting to download data from", url); 12 | setTimeout(function down() { 13 | console.log("Downloading completed"); 14 | const content = "ABCDEF"; // assume dummy download content 15 | cb(content); 16 | }, 10000); 17 | } 18 | 19 | function writeFile(data, cb) { 20 | /** 21 | * writes the given data into a new file 22 | */ 23 | console.log("Started writing a file with", data); 24 | setTimeout(function wrtie() { 25 | console.log("Completed writing the data in a file"); 26 | const filename = "file.txt"; 27 | cb(filename); 28 | }, 5000); 29 | } 30 | 31 | function upload(url, file, cb) { 32 | /** 33 | * uploads the data from a file to a given url 34 | */ 35 | console.log("Started uploading", file, "on", url); 36 | setTimeout(function up() { 37 | console.log("upload completed"); 38 | const response = "SUCCESS"; 39 | cb(response); 40 | }, 2000); 41 | } 42 | 43 | download("www.xyz.com", function processDownload(content) { 44 | console.log("We are now going to process the downloaded data"); 45 | writeFile(content, function processWrite(filename) { 46 | console.log("We have downloaded and written the file, now will upload"); 47 | upload("www.upload.com", filename, function processUpload(response) { 48 | console.log("we have uploaded with", response); 49 | }); 50 | }); 51 | }); -------------------------------------------------------------------------------- /JavaScript/Chapter 09 - Part - 4 Promises and callbacks practice/Code/promiseimpl.js: -------------------------------------------------------------------------------- 1 | // Tasks: (Don't use promises only use promises) 2 | // 1. Write a function to download data from a url 3 | // 2. Write a function to save that downloaded data in a file and return the filename 4 | // 3. Write a function to upload the file written in previous step to a newurl 5 | 6 | function download(url) { 7 | return new Promise(function exec(resolve, reject) { 8 | console.log("Starting to download data from", url); 9 | setTimeout(function down() { 10 | console.log("Downloading completed"); 11 | const content = "ABCDEF"; // assume dummy download content 12 | resolve(content); 13 | }, 6000); 14 | }); 15 | } 16 | 17 | function writeFile(data) { 18 | return new Promise(function exec(resolve, reject) { 19 | console.log("Started writing a file with", data); 20 | setTimeout(function wrtie() { 21 | console.log("Completed writing the data in a file"); 22 | const filename = "file.txt"; 23 | resolve(filename); 24 | }, 5000); 25 | }) 26 | } 27 | 28 | function uploadData(file, url) { 29 | return new Promise(function exec(resolve, reject) { 30 | console.log("Started uploading", file, "on", url); 31 | setTimeout(function up() { 32 | console.log("upload completed"); 33 | const response = "SUCCESS"; 34 | resolve(response); 35 | }, 2000); 36 | }) 37 | } 38 | 39 | download("www.xyz.com") 40 | .then(function processDownload(value) { 41 | console.log("downloading done with following value", value); 42 | return writeFile(value); 43 | }) 44 | .then(function processWrite(value) { 45 | console.log("data written in the file with name", value); 46 | return uploadData(value, "www.upload.com"); 47 | }) 48 | .then(function processUpload(value) { 49 | console.log("we have uploaded with", value); 50 | }); -------------------------------------------------------------------------------- /JavaScript/Chapter 09 - Part - 4 Promises and callbacks practice/Promises-practise-question.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/JavaScript/Chapter 09 - Part - 4 Promises and callbacks practice/Promises-practise-question.png -------------------------------------------------------------------------------- /JavaScript/Chapter 10 - Closures - Iterators and Generators/Closures_Iterators_And_Generators.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/JavaScript/Chapter 10 - Closures - Iterators and Generators/Closures_Iterators_And_Generators.pdf -------------------------------------------------------------------------------- /JavaScript/Chapter 10 - Closures - Iterators and Generators/Code/closures_Demo.js: -------------------------------------------------------------------------------- 1 | function DO(task) { // local to DO is task 2 | setTimeout(function exec() { 3 | console.log(task); 4 | }, 2000); 5 | } 6 | 7 | DO("dkfbjh"); 8 | console.log("end"); -------------------------------------------------------------------------------- /JavaScript/Chapter 10 - Closures - Iterators and Generators/Code/generator_demo.js: -------------------------------------------------------------------------------- 1 | function* fetchNextElement() { // generator function 2 | console.log("I am inside the generator function"); 3 | yield 1; 4 | yield 2; 5 | console.log("somewhere in the middle"); 6 | yield 3; 7 | yield 4; 8 | } 9 | 10 | const iter = fetchNextElement(); 11 | 12 | console.log("1st",iter.next()); 13 | console.log("2nd",iter.next()); 14 | console.log("3rd",iter.next()); 15 | console.log("4th",iter.next()); 16 | console.log("5th",iter.next()); 17 | console.log("6th",iter.next()); -------------------------------------------------------------------------------- /JavaScript/Chapter 10 - Closures - Iterators and Generators/Code/intro_to_closures.js: -------------------------------------------------------------------------------- 1 | function process() { 2 | let i = 0; 3 | function innerProcess() { 4 | i += 1; // i = 0 5 | return i; 6 | } 7 | return innerProcess; // we are not calling the function, we are just returning 8 | } 9 | 10 | let res = process(); 11 | 12 | console.log(res); 13 | 14 | console.log("first time calling res", res()); 15 | console.log("second time calling res", res()); 16 | console.log("third time calling res", res()); -------------------------------------------------------------------------------- /JavaScript/Chapter 10 - Closures - Iterators and Generators/Code/iterators_self_demo.js: -------------------------------------------------------------------------------- 1 | function fetchNextElement(array) { 2 | let idx = 0; 3 | function next() { 4 | if(idx == array.length) { 5 | return {value: undefined, done: true}; 6 | } 7 | const nextElement = array[idx]; 8 | idx++; 9 | return {value: nextElement, done: false}; 10 | } 11 | return {next}; 12 | } 13 | 14 | // somehwere we consume it 15 | 16 | const automaticFetcher = fetchNextElement([99,11,12,13,0,1,2,3,4]); // inside automatic fetcher variable we can store next function 17 | console.log(automaticFetcher.next()); 18 | console.log(automaticFetcher.next()); 19 | console.log(automaticFetcher.next()); 20 | console.log(automaticFetcher.next()); 21 | console.log(automaticFetcher.next()); 22 | -------------------------------------------------------------------------------- /JavaScript/Chapter 11 - Async-Await - Try and Catch/Async-Await.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/JavaScript/Chapter 11 - Async-Await - Try and Catch/Async-Await.pdf -------------------------------------------------------------------------------- /JavaScript/Chapter 11 - Async-Await - Try and Catch/Code/async_await_Demo.js: -------------------------------------------------------------------------------- 1 | function download(url) { 2 | return new Promise(function exec(resolve, reject) { 3 | console.log("Starting to download data from", url); 4 | setTimeout(function down() { 5 | console.log("Downloading completed"); 6 | const content = "ABCDEF"; // assume dummy download content 7 | resolve(content); 8 | }, 1000); 9 | }); 10 | } 11 | 12 | function writeFile(data) { 13 | return new Promise(function exec(resolve, reject) { 14 | console.log("Started writing a file with", data); 15 | setTimeout(function wrtie() { 16 | console.log("Completed writing the data in a file"); 17 | const filename = "file.txt"; 18 | resolve(filename); 19 | }, 5000); 20 | }) 21 | } 22 | 23 | function uploadData(file, url) { 24 | return new Promise(function exec(resolve, reject) { 25 | console.log("Started uploading", file, "on", url); 26 | setTimeout(function up() { 27 | console.log("upload completed"); 28 | const response = "SUCCESS"; 29 | resolve(response); 30 | }, 2000); 31 | }) 32 | } 33 | 34 | async function steps() { 35 | console.log("starting steps"); 36 | const downloadedData = await download("www.xyz.com"); 37 | console.log("data downloaded is", downloadedData); 38 | const fileWritten = await writeFile(downloadedData); 39 | console.log("fiele written is", fileWritten); 40 | const uploadResponse = await uploadData(fileWritten, "www.drive.google.com"); 41 | console.log("Upload response is", uploadResponse); 42 | return uploadResponse; 43 | } 44 | 45 | steps().then((value) => console.log("we have completed steps with", value)); 46 | console.log("outside"); 47 | for(let i = 0 ; i < 10000000000; i++) { 48 | 49 | } 50 | setTimeout(function f() {console.log("timer done")}, 4000); 51 | console.log("for loop done"); -------------------------------------------------------------------------------- /JavaScript/Chapter 11 - Async-Await - Try and Catch/Code/catchpromise.js: -------------------------------------------------------------------------------- 1 | function download(url) { 2 | return new Promise(function exec(resolve, reject) { 3 | console.log("Starting to download data from", url); 4 | setTimeout(function down() { 5 | console.log("Downloading completed"); 6 | const content = "ABCDEF"; // assume dummy download content 7 | resolve(content); 8 | }, 1000); 9 | }); 10 | } 11 | 12 | function writeFile(data) { 13 | return new Promise(function exec(resolve, reject) { 14 | console.log("Started writing a file with", data); 15 | setTimeout(function wrtie() { 16 | console.log("Completed writing the data in a file"); 17 | const filename = "file.txt"; 18 | resolve(filename); 19 | }, 5000); 20 | }) 21 | } 22 | 23 | function uploadData(file, url) { 24 | return new Promise(function exec(resolve, reject) { 25 | console.log("Started uploading", file, "on", url); 26 | setTimeout(function up() { 27 | console.log("upload completed"); 28 | const response = "SUCCESS"; 29 | resolve(response); 30 | }, 2000); 31 | }) 32 | } 33 | 34 | 35 | 36 | download("www.xyz.com") 37 | .then( 38 | function processDownload(value) { 39 | console.log("downloading done with following value", value); 40 | return writeFile(value); 41 | }, 42 | ) 43 | .then( 44 | function processWrite(value) { 45 | console.log("data written in the file with name", value); 46 | return uploadData(value, "www.upload.com"); 47 | }, 48 | ) 49 | .then( 50 | function processUpload(value) { 51 | console.log("we have uploaded with", value); 52 | }, 53 | ) 54 | .catch(function f(err) { 55 | console.log("catching error", err); 56 | }) 57 | .finally(function final() { 58 | console.log("executing finally") 59 | }) -------------------------------------------------------------------------------- /JavaScript/Chapter 11 - Async-Await - Try and Catch/Code/demo.js: -------------------------------------------------------------------------------- 1 | const timeout = (ms) => new Promise(resolve => setTimeout(resolve, ms)); 2 | 3 | const customFetch = async (url, options = {}) => { 4 | const { timeoutMs = 30000, ...fetchOptions } = options; 5 | 6 | const controller = new AbortController(); 7 | const timeoutPromise = timeout(timeoutMs).then(() => controller.abort()); 8 | 9 | const responsePromise = fetch(url, { signal: controller.signal, ...fetchOptions }); 10 | 11 | const response = await Promise.race([responsePromise, timeoutPromise]); 12 | 13 | if (!response.ok) { 14 | throw new Error(`Request failed with status ${response.status}`); 15 | } 16 | 17 | return response.json(); 18 | }; 19 | 20 | const executeTask = async (task, ...args) => { 21 | const { timeoutMs = 30000 } = task; 22 | 23 | const timeoutPromise = timeout(timeoutMs).then(() => { 24 | throw new Error(`Task timed out after ${timeoutMs} ms`); 25 | }); 26 | 27 | const taskPromise = task(...args); 28 | 29 | const result = await Promise.race([taskPromise, timeoutPromise]); 30 | 31 | return result; 32 | }; 33 | 34 | const tasks = [ 35 | async () => await customFetch('endpointA'), 36 | async (dataFromA) => await customFetch(`endpointB?param=${dataFromA.param}`), 37 | async (dataFromAandB) => await customFetch(`endpointC?id=${dataFromAandB.id}`), 38 | async (dataFromAandBandC) => { 39 | // Write output to file 40 | return true; 41 | }, 42 | async () => { 43 | // Cleanup resources 44 | return true; 45 | } 46 | ]; 47 | 48 | const executeTaskList = async (taskList) => { 49 | let previousResult = null; 50 | 51 | for (const task of taskList) { 52 | try { 53 | previousResult = await executeTask(task, previousResult); 54 | } catch (error) { 55 | console.error(`Task failed with error: ${error.message}`); 56 | } 57 | } 58 | }; 59 | 60 | executeTaskList(tasks); 61 | -------------------------------------------------------------------------------- /JavaScript/Chapter 11 - Async-Await - Try and Catch/Code/errorasyncawait.js: -------------------------------------------------------------------------------- 1 | function download(url) { 2 | return new Promise(function exec(resolve, reject) { 3 | console.log("Starting to download data from", url); 4 | setTimeout(function down() { 5 | console.log("Downloading completed"); 6 | const content = "ABCDEF"; // assume dummy download content 7 | resolve(content); 8 | }, 1000); 9 | }); 10 | } 11 | 12 | 13 | async function steps() { 14 | try { 15 | console.log("starting steps"); 16 | const downloadedData = await download("www.xyz.com"); 17 | return downloadedData; 18 | } catch(error) { 19 | console.log("we have handled the error", error); 20 | } finally { 21 | console.log("ending") 22 | } 23 | 24 | } 25 | 26 | steps(); -------------------------------------------------------------------------------- /JavaScript/Chapter 11 - Async-Await - Try and Catch/Code/errorpromise.js: -------------------------------------------------------------------------------- 1 | function download(url) { 2 | return new Promise(function exec(resolve, reject) { 3 | console.log("Starting to download data from", url); 4 | setTimeout(function down() { 5 | console.log("Downloading completed"); 6 | const content = "ABCDEF"; // assume dummy download content 7 | reject(content); 8 | }, 1000); 9 | }); 10 | } 11 | 12 | function writeFile(data) { 13 | return new Promise(function exec(resolve, reject) { 14 | console.log("Started writing a file with", data); 15 | setTimeout(function wrtie() { 16 | console.log("Completed writing the data in a file"); 17 | const filename = "file.txt"; 18 | resolve(filename); 19 | }, 5000); 20 | }) 21 | } 22 | 23 | function uploadData(file, url) { 24 | return new Promise(function exec(resolve, reject) { 25 | console.log("Started uploading", file, "on", url); 26 | setTimeout(function up() { 27 | console.log("upload completed"); 28 | const response = "SUCCESS"; 29 | resolve(response); 30 | }, 2000); 31 | }) 32 | } 33 | 34 | 35 | 36 | download("www.xyz.com") 37 | .then( 38 | function processDownload(value) { 39 | console.log("downloading done with following value", value); 40 | return writeFile(value); 41 | }, 42 | function downloadreject(value) { 43 | console.log("download reject", value); 44 | throw value 45 | } 46 | ) 47 | .then( 48 | function processWrite(value) { 49 | console.log("data written in the file with name", value); 50 | return uploadData(value, "www.upload.com"); 51 | }, 52 | function writereject(value) { 53 | console.log("write reject", value); 54 | throw value 55 | } 56 | ) 57 | .then( 58 | function processUpload(value) { 59 | console.log("we have uploaded with", value); 60 | }, 61 | function uploadreject(value) { 62 | console.log("upload reject", value); 63 | } 64 | ); -------------------------------------------------------------------------------- /JavaScript/Chapter 11 - Async-Await - Try and Catch/Code/generator_adv_demo.js: -------------------------------------------------------------------------------- 1 | function* fetchNextElement() { 2 | console.log("inside generator"); 3 | const x = 10; 4 | console.log(yield 11); 5 | // yield {name: "Sanket"}; 6 | console.log("entering after a yield"); 7 | const y = x + (yield 30); 8 | console.log("Value of y is", y); 9 | } 10 | console.log("start"); 11 | const iter = fetchNextElement(); 12 | console.log("called generator") 13 | console.log("first", iter.next(10)); 14 | console.log("second", iter.next(55)); 15 | console.log("third", iter.next(17)); -------------------------------------------------------------------------------- /JavaScript/Chapter 11 - Async-Await - Try and Catch/Code/promiseall.js: -------------------------------------------------------------------------------- 1 | function download(url, time) { 2 | return new Promise(function exec(resolve, reject) { 3 | console.log("Starting to download data from", url); 4 | setTimeout(function down() { 5 | console.log("Downloading completed"); 6 | const content = "ABCDEF"; // assume dummy download content 7 | if(time > 1000) { 8 | reject("err") 9 | } else 10 | resolve(content); 11 | }, time); 12 | }); 13 | } 14 | 15 | 16 | const p1 = download("www.abc1.com", 5000); 17 | const p2 = download("www.abc2.com", 1000); 18 | const p3 = download("www.abc3.com", 3000); 19 | Promise.all([p1, p2, p3]).then(function fullfillHandler(values) { 20 | console.log(values); 21 | }) -------------------------------------------------------------------------------- /JavaScript/Chapter 11 - Async-Await - Try and Catch/Code/promises_generator.js: -------------------------------------------------------------------------------- 1 | function download(url) { 2 | return new Promise(function exec(resolve, reject) { 3 | console.log("Starting to download data from", url); 4 | setTimeout(function down() { 5 | console.log("Downloading completed"); 6 | const content = "ABCDEF"; // assume dummy download content 7 | resolve(content); 8 | }, 1000); 9 | }); 10 | } 11 | 12 | function writeFile(data) { 13 | return new Promise(function exec(resolve, reject) { 14 | console.log("Started writing a file with", data); 15 | setTimeout(function wrtie() { 16 | console.log("Completed writing the data in a file"); 17 | const filename = "file.txt"; 18 | resolve(filename); 19 | }, 5000); 20 | }) 21 | } 22 | 23 | function uploadData(file, url) { 24 | return new Promise(function exec(resolve, reject) { 25 | console.log("Started uploading", file, "on", url); 26 | setTimeout(function up() { 27 | console.log("upload completed"); 28 | const response = "SUCCESS"; 29 | resolve(response); 30 | }, 2000); 31 | }) 32 | } 33 | 34 | function doAfterReceiving(value) { 35 | 36 | let future = iter.next(value); 37 | console.log("future is", future); 38 | if(future.done) return; 39 | future.value.then(doAfterReceiving); 40 | } 41 | 42 | function* steps() { 43 | const downloadedData = yield download("www.xyz.com"); 44 | console.log("data downloaded is", downloadedData); 45 | const fileWritten = yield writeFile(downloadedData); 46 | console.log("fiele written is", fileWritten); 47 | const uploadResponse = yield uploadData(fileWritten, "www.drive.google.com"); 48 | console.log("Upload response is", uploadResponse); 49 | return uploadResponse; 50 | } 51 | 52 | const iter = steps(); 53 | const future = iter.next(); 54 | for(let i = 0; i < 10000000000; i++) { 55 | 56 | } 57 | future.value.then(doAfterReceiving); 58 | 59 | -------------------------------------------------------------------------------- /JavaScript/Chapter 12 - class, object, this keyword/Code/class.js: -------------------------------------------------------------------------------- 1 | class Product { 2 | name; // no need of let var const 3 | price; 4 | discount; 5 | desc; 6 | 7 | display() { 8 | // no need of function keyword 9 | } 10 | 11 | buy() { 12 | 13 | } 14 | 15 | wishlist() { 16 | 17 | } 18 | 19 | } 20 | 21 | // syntax to create an object 22 | const p = new Product(); -------------------------------------------------------------------------------- /JavaScript/Chapter 12 - class, object, this keyword/Code/this.demo3.js: -------------------------------------------------------------------------------- 1 | const iphone = { 2 | name: "iphone", 3 | price: 100000, 4 | rating: 4.8, 5 | display: () => { 6 | 7 | let iphoneRed = { 8 | name: "Iphone red", 9 | price: 110000, 10 | print: () => { 11 | console.log(this); 12 | } 13 | } 14 | iphoneRed.print(); 15 | 16 | } 17 | } 18 | 19 | iphone.display(); -------------------------------------------------------------------------------- /JavaScript/Chapter 12 - class, object, this keyword/Code/this_demo.js: -------------------------------------------------------------------------------- 1 | let iphone = { 2 | name: "Iphone 13 pro", 3 | price: 100000, 4 | descrption: "The new apple iphone 13 pro.", 5 | rating: 4.8, 6 | 7 | display() { 8 | console.log("first display", this); 9 | } 10 | } 11 | 12 | let macbook = { 13 | name: "Macbook M2", 14 | price: 125000, 15 | descrption: "The new apple macbook m2.", 16 | rating: 4.9, 17 | 18 | display() { 19 | console.log("second display", this); 20 | } 21 | } 22 | 23 | macbook.display(); 24 | 25 | console.log(this); 26 | 27 | -------------------------------------------------------------------------------- /JavaScript/Chapter 12 - class, object, this keyword/Code/this_demo2.js: -------------------------------------------------------------------------------- 1 | const iphone = { 2 | name: "Iphone", 3 | category: "electronics", 4 | price: 10000, 5 | rating: 4.8, 6 | display: () => { 7 | console.log(this); 8 | } 9 | } 10 | 11 | const macbook = { 12 | name: "macbook", 13 | category: "electronics", 14 | price: 10000, 15 | rating: 4.8, 16 | display: function () { 17 | console.log(this); 18 | } 19 | } 20 | 21 | macbook.display(); 22 | iphone.display(); -------------------------------------------------------------------------------- /JavaScript/Chapter 12 - class, object, this keyword/class, this.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/JavaScript/Chapter 12 - class, object, this keyword/class, this.pdf -------------------------------------------------------------------------------- /JavaScript/Chapter 13 - new keyword, constructor function, private variables/Code/functionConstructor.js: -------------------------------------------------------------------------------- 1 | function Product(n, p, d) { 2 | name = n; 3 | this.price = p; 4 | this.description = d; 5 | 6 | this.display = function () { 7 | console.log(name, this.price); 8 | } 9 | } 10 | const p = new Product("bag", 100, "cool new bag"); 11 | p.display(); -------------------------------------------------------------------------------- /JavaScript/Chapter 13 - new keyword, constructor function, private variables/Code/new_keyword_demo.js: -------------------------------------------------------------------------------- 1 | class Product { 2 | #name; // private 3 | #price; 4 | // description; 5 | 6 | constructor(n, p, d) { 7 | this.#name = n; 8 | this.#price = p; 9 | this.description = d; 10 | // return "10"; // primitive -> no effect 11 | // return {x: 10}; 12 | //return this; // if you dont return anything, it is equal to saying return this; 13 | } 14 | 15 | set name(n) { 16 | if(typeof(n) != 'string') { 17 | console.log("invalid name passed"); 18 | return; 19 | } 20 | this.#name = n; 21 | } 22 | 23 | setPrice(p) { 24 | if(p < 0) return; 25 | this.#price = p; 26 | } 27 | 28 | get name() { 29 | return this.#name; 30 | } 31 | 32 | display() { 33 | // print the product 34 | console.log(this.#name, this.#price, this.description); 35 | } 36 | } 37 | 38 | const p = new Product("Bag", 100, "a cool bag"); 39 | p.name = "Iphone"; 40 | console.log(p); 41 | // console.log(p.name); -------------------------------------------------------------------------------- /JavaScript/Chapter 13 - new keyword, constructor function, private variables/new, constructor in JS.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/JavaScript/Chapter 13 - new keyword, constructor function, private variables/new, constructor in JS.pdf -------------------------------------------------------------------------------- /JavaScript/Chapter 14 - Prototype based inheritance/Prototyple Chaining .pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/JavaScript/Chapter 14 - Prototype based inheritance/Prototyple Chaining .pdf -------------------------------------------------------------------------------- /Namastey_JS.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/Namastey_JS.pdf -------------------------------------------------------------------------------- /NodeJS/Chapter 01 - Intro To Node Js/Intro to NodeJs.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/NodeJS/Chapter 01 - Intro To Node Js/Intro to NodeJs.pdf -------------------------------------------------------------------------------- /NodeJS/Chapter 01 - Intro To Node Js/diff_node_browser.js: -------------------------------------------------------------------------------- 1 | const x = setTimeout(function exec() { 2 | console.log("completed timer"); 3 | }, 10000); 4 | 5 | console.log(x); 6 | clearTimeout(x); -------------------------------------------------------------------------------- /NodeJS/Chapter 01 - Intro To Node Js/globals_node.js: -------------------------------------------------------------------------------- 1 | console.log(process.env); 2 | console.log(module); 3 | console.log(require); 4 | console.log(__dirname); 5 | console.log(global); -------------------------------------------------------------------------------- /NodeJS/Chapter 02 - Modules in Nodejs/Module in Nodejs.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachinDev07/JS-Backend/7031ae01c19b3d3b00a9d6e5043b95677ebf9a6f/NodeJS/Chapter 02 - Modules in Nodejs/Module in Nodejs.pdf -------------------------------------------------------------------------------- /READMe.md: -------------------------------------------------------------------------------- 1 | # ❤️ BACKEND IN NODEJS 🙏 2 | ### _[Backend In NodeJs]. This repository for Assignment &Notes taken during the Learning._ 3 | 4 | ## 📚 Computer Networks Notes 5 | - 📖 [_Handwritten Notes Link_](https://drivee.google.com/file/d/1sixK5Pjb2vs-jVNtwYuRYQk_ZUJkcfut/view?usp=sharing) 6 | 7 | ## 📚 Namastey JavaScript Notes 8 | - 📖 [_Handwritten Notes Link_](https://drive.google.com/file/d/1uP0lj8GFqUm5dgUnEo2-dtFdTuMFSrav/view?usp=sharing) 9 | ## 📚 [_Chapter 01 - Operators_](https://tinyurl.com/2p8futts) 10 | - 👨‍💻 [_Code Solution_](https://tinyurl.com/mry4f83t) 11 | - 📖 [_Theory Solution_](https://tinyurl.com/2p8fspya) [`Credit - Sajjad S.`](https://www.linkedin.com/in/sajjadsalaria/) 12 | 13 | ## 📚 [_Chapter 02 - Introduction To Coercion_](https://tinyurl.com/coercionss) 14 | - 👨‍💻 [_Code Solution_](https://tinyurl.com/coercioncode) 15 | - 📖 [_Theory Solution_](https://tinyurl.com/ys824c6u) 16 | - 📝 [_Hand Written Notes of Live Class_](https://drive.google.com/file/d/1VLwBOzXOJqO7gafS-jk64ytzUGyKJYC7/view?usp=sharing) 17 | 18 | ## 📚 [_Chapter 03 - Scopes And Function Expression_](https://tinyurl.com/scopesAndFunctionExpression) 19 | - 👨‍💻 [_Code Solution_](https://tinyurl.com/scopesCode) 20 | - 📖 [_Theory Solution_](https://tinyurl.com/scopesTheory) [`Credit - Sajjad S.`](https://www.linkedin.com/in/sajjadsalaria/) 21 | - 🔍 Scope based problems 22 | - [freeCodeCamp problem](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/global-scope-and-functions) 23 | - [freeCodeCamp problem](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/local-scope-and-functions) 24 | - [freeCodeCamp problem](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/global-vs--local-scope-in-functions) 25 | - 📝 [_Hand Written Notes of Live Class_](https://drive.google.com/file/d/1vRezgwmXytXcqNPAOG7xtGhXx9-Mb53Y/view?usp=sharing) 26 | 27 | ## 📚 [_Chapter 04 - Introduction To Callback & Inversion Of Control_](https://tinyurl.com/callbackAndInversionOfControl) 28 | - 👨‍💻 [_Code Solution_](https://tinyurl.com/callbackCode) 29 | - 📖 [_Theory Solution_](https://tinyurl.com/callbackTheory) [`Credit - Sajjad S.`](https://www.linkedin.com/in/sajjadsalaria/) 30 | - 📝 [_Hand Written Notes of Live Class_](https://drive.google.com/file/d/1efCCLd3vggFG4vPJnnhwNnM_q5po40XX/view?usp=sharing) 31 | 32 | ## 📚 [_Chapter 05 - How Runtime Helps in Async Nature of JS_](https://tinyurl.com/asyncNature) 33 | - 👨‍💻 [_Code Solution_](https://tinyurl.com/asyncCode) 34 | - 📖 [_Theory Solution_](https://tinyurl.com/asyncTheory) [`Credit - Sajjad S.`](https://www.linkedin.com/in/sajjadsalaria/) 35 | - 📝 [_Hand Written Notes of Live Class_](https://drive.google.com/file/d/1ew8Za_KirMdhYZk2pvajDzaUyLBhjE68/view?usp=sharing) 36 | 37 | ## 📚 [_Chapter 06 - Introduction To Promises_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/JavaScript/Chapter%2006%20-%20Introduction%20To%20Promises) (Date: 21-02-2023) 38 | - 👨‍💻 [_Code Solution_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/JavaScript/Chapter%2006%20-%20Introduction%20To%20Promises/Code) 39 | - 📖 [_Theory Solution_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/JavaScript/Chapter%2006%20-%20Introduction%20To%20Promises/Theory) [`Credit - Sajjad S.`](https://www.linkedin.com/in/sajjadsalaria/) 40 | - 📝 [_Hand Written Notes of Live Class_](https://drive.google.com/file/d/1shkT8joyN6bMNiDbyPTLmAOMys6wxv-A/view?usp=sharing) 41 | 42 | ## 📚 [_Chapter 07 - Part-2 Promises : How to Consume a Promise_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/JavaScript/Chapter%2007%20-%20How%20to%20consume%20a%20promise-%20Part-2) (Date: 23-02-2023) 43 | - 👨‍💻 [_Code Solution_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/JavaScript/Chapter%2007%20-%20How%20to%20consume%20a%20promise-%20Part-2/Code) 44 | - 📝 [_Hand Written Notes of Live Class_](https://drive.google.com/file/d/1u4_viuMVeezWrcCGcy4fMPWhSmU5tfJd/view?usp=sharing) 45 | 46 | ## 📚 [_Chapter 08 - Part-3 Promises Practice & .then() Concept_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/JavaScript/Chapter%2008%20-%20Part%20-%203%20%20Promises%20practice) (Date: 25-02-2023) 47 | - 👨‍💻 [_Code Solution_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/JavaScript/Chapter%2008%20-%20Part%20-%203%20%20Promises%20practice/Code) 48 | - 📖 [_Theory Solution_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/JavaScript/Chapter%2008%20-%20Part%20-%203%20%20Promises%20practice/Theory) 49 | - 📝 [_Hand Written Notes of Live Class_](https://drive.google.com/file/d/1uEFACA5cA5Fbh0i8FnwPqKAi-3tvMP4r/view?usp=sharing) 50 | 51 | ## 📚 [_Chapter 09 - Part-4 Promises and Callbacks Practice_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/JavaScript/Chapter%2009%20-%20Part%20-%204%20%20Promises%20and%20callbacks%20practice) (Date: 26-02-2023) 52 | - 👨‍💻 [_Code Solution_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/JavaScript/Chapter%2009%20-%20Part%20-%204%20%20Promises%20and%20callbacks%20practice/Code) 53 | - 📝 [_Practice Question Link_](https://drive.google.com/file/d/1hnYKAaeyyE3TMkYKBIVyNbRhXKnK0qmd/view?usp=sharing) 54 | 55 | ## 📚 [_Chapter 10 - Closures, Iterators and Generators - Road to Async and Await_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/JavaScript/Chapter%2010%20-%20Closures%20-%20Iterators%20and%20Generators) (Date: 28-02-2023) 56 | - 👨‍💻 [_Code Solution_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/JavaScript/Chapter%2010%20-%20Closures%20-%20Iterators%20and%20Generators/Code) 57 | - 📝 [_Hand Written Notes of Live Class_](https://drive.google.com/file/d/1uJCrxKv4cvO5PL53YOQBk85DGpzrHVNX/view?usp=sharing) 58 | 59 | ## 📚 [_Chapter 11 - Async/Await - Try...Catch_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/JavaScript/Chapter%2011%20-%20Async-Await%20-%20Try%20and%20Catch) (Date: 04-03-2023) 60 | - 👨‍💻 [_Code Solution_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/JavaScript/Chapter%2011%20-%20Async-Await%20-%20Try%20and%20Catch/Code) 61 | - 📝 [_Hand Written Notes of Live Class_](https://drive.google.com/file/d/1maZyIMYM5U7uD5DAcdjQWpLQRWz6Sy54/view?usp=sharing) 62 | 63 | ## 📚 [_Chapter 12 - Class, Object, this keyword_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/JavaScript/Chapter%2012%20-%20class%2C%20object%2C%20%20this%20keyword) (Date: 16-04-2023) 64 | - 👨‍💻 [_Code Solution_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/JavaScript/Chapter%2012%20-%20class%2C%20object%2C%20%20this%20keyword/Code) 65 | - 📝 [_Hand Written Notes of Live Class_](https://drive.google.com/file/d/1mXeun2uPn2cC6u0zfYDltXobLIBBlwb4/view?usp=sharing) 66 | 67 | ## 📚 [_Chapter 13 - new Keyword, function constructor_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/JavaScript/Chapter%2013%20-%20new%20keyword%2C%20constructor%20function%2C%20private%20variables) (Date: 18-04-2023) 68 | - 👨‍💻 [_Code Solution_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/JavaScript/Chapter%2013%20-%20new%20keyword%2C%20constructor%20function%2C%20private%20variables/Code) 69 | - 📝 [_Hand Written Notes of Live Class_](https://drive.google.com/file/d/1QHn0tOYcwS7ULruPuDuUCkF3VWqxjmFt/view?usp=sharing) 70 | 71 | ## 📚 [_Chapter 14 - Prototyple based inheritance_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/JavaScript/Chapter%2014%20-%20Prototype%20based%20inheritance) (Date: 23-04-2023) 72 | - 📝 [_Hand Written Notes of Live Class_](https://drive.google.com/file/d/1duuUqK7K0A3rHEnGuw18oEbF5--10_dl/view?usp=sharing) 73 | 74 | 75 | ## 📚 Database Management System 76 | ## 📚 [_Introduction To Databases And DBMS_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/DBMS/Introduction%20To%20Databases%20and%20DBMS) (Date: 05-03-2023) 77 | - 👨‍💻 [_Digital Notes of Live Class_](https://drive.google.com/file/d/120d3D5ZOOA03nfPV1rXm87eeryj4kZWf/view?usp=sharing) 78 | - 📝 [_Hand Written Notes of Live Class_](https://drive.google.com/file/d/1o3uqXUuyJITDlmq85_9s63URUa0Wm2SY/view?usp=sharing) 79 | 80 | ## 📚 [_Chapter 01 - SQL_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/DBMS/SQL1) (Date: 09-03-2023) 81 | - 📝 [_Hand Written Notes of Live Class_](https://drive.google.com/file/d/1062acc_kFyOhv92UFxIlXqUM0SB6C34O/view?usp=sharing) 82 | - 📝 [_Good Notes of Live Class_](https://github.com/Sachin-RJ7/JS-Backend/blob/master/DBMS/SQL1/SQL1.md) [`Credit - Sajjad S.`](https://www.linkedin.com/in/sajjadsalaria/) 83 | - 👨‍💻 [_InterviewBit MySql commands link_](https://www.interviewbit.com/blog/mysql-commands/) 84 | - 👨‍💻 [_W3 Schools link_](https://www.w3schools.com/mysql/mysql_sql.asp) 85 | 86 | ## 📚 [_Chapter 02 - SQL_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/DBMS/SQL2) (Date: 10-03-2023) 87 | - 📝 [_Class Notes of Live Class_](https://drive.google.com/file/d/1R9DXkh0waSGqakEvP3Q5AJBgrpaVEloU/view?usp=sharing) 88 | - 📝 [_Hand Written Notes of Live Class_](https://github.com/Sachin-RJ7/JS-Backend/blob/master/DBMS/SQL2/notes.md) 89 | - 📝 [_Good Notes of Live Class_](https://github.com/Sachin-RJ7/JS-Backend/blob/master/DBMS/SQL2/SQL2.md) [`Credit - Sajjad S.`](https://www.linkedin.com/in/sajjadsalaria/) 90 | 91 | ## 📚 [_Chapter 03 - SQL_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/DBMS/SQL3) (Date: 11-03-2023) 92 | - 📝 [_Hand Written Notes of Live Class_](https://drive.google.com/file/d/14Cctr_PZl6RdsvGOWALANTH8dKB3egq2/view?usp=sharing) 93 | - 📝 [_Good Notes of Live Class_](https://github.com/Sachin-RJ7/JS-Backend/blob/master/DBMS/SQL3/SQL3.md) [`Credit - Sajjad S.`](https://www.linkedin.com/in/sajjadsalaria/) 94 | 95 | ## 📚 [_Chapter 04 - Road to Normalisation_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/DBMS/Road%20To%20Normalisation) (Date: 12-03-2023) 96 | - 📝 [_Hand Written Notes of Live Class_](https://drive.google.com/file/d/15abeu-izNhzlqF8FSuNspcIQuI9CEvF7/view?usp=sharing) 97 | - 📝 [_Notes of Live Class_](https://github.com/Sachin-RJ7/JS-Backend/blob/master/DBMS/Road%20To%20Normalisation/Normalization-I.md) [`Credit - Sajjad S.`](https://www.linkedin.com/in/sajjadsalaria/) 98 | 99 | ## 📚 [_Chapter 05 - Normalisation_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/DBMS/sNormalisation%20Part%202) (Date: 14-03-2023) 100 | - 📝 [_Hand Written Notes of Live Class_](https://drive.google.com/file/d/1QjNjcZiafn2kY6T5aPCXIpQK_KM9UtyG/view?usp=sharing) 101 | - 📝 [_Notes of Live Class_](https://github.com/Sachin-RJ7/JS-Backend/blob/master/DBMS/sNormalisation%20Part%202/Normalization-II.md) [`Credit - Sajjad S.`](https://www.linkedin.com/in/sajjadsalaria/) 102 | 103 | ## 📚 [_Chapter 06 - Normalisation_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/DBMS/sNormalisation%20Part%203) (Date: 18-03-2023) 104 | - 📝 [_Digital Notes of Live Class_](https://github.com/Sachin-RJ7/JS-Backend/blob/master/DBMS/sNormalisation%20Part%203/Black%20Paper%20Landscape%20(13).pdf) 105 | - 📝 [_Question 1_](https://github.com/Sachin-RJ7/JS-Backend/blob/master/DBMS/sNormalisation%20Part%203/hw.md) 106 | - 📝 [_Question 2_](https://github.com/Sachin-RJ7/JS-Backend/blob/master/DBMS/sNormalisation%20Part%203/requirements.md) 107 | 108 | 109 | ## 📚 Introduction to Node Js 110 | ## 📚 [_Chapter 01 - Features of NodeJs_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/NodeJS/Chapter%2001%20-%20Intro%20To%20Node%20Js) (Date: 06-04-2023) 111 | - 👨‍💻 [_Digital Notes of Live Class_](https://github.com/Sachin-RJ7/JS-Backend/blob/master/NodeJS/Chapter%2001%20-%20Intro%20To%20Node%20Js/globals_node.js) 112 | - 👨‍💻 [_Digital Notes of Live Class_](https://github.com/Sachin-RJ7/JS-Backend/blob/master/NodeJS/Chapter%2001%20-%20Intro%20To%20Node%20Js/diff_node_browser.js) 113 | - 📝 [_Hand Written Notes of Live Class_](https://drive.google.com/file/d/1wf0pYl1oa44Kgu_ooejJG8YnAyFCdxO0/view?usp=sharing) 114 | 115 | 116 | ## 📚 [_Chapter 02 - Modules in NodeJS_](https://github.com/Sachin-RJ7/JS-Backend/tree/master/NodeJS/Chapter%2002%20-%20Modules%20in%20Nodejs) (Date: 09-04-2023) 117 | - 📝 [_Hand Written Notes of Live Class_](https://drive.google.com/file/d/1qiVFwwrDOnN0Kly2w4ufXDIDflQNkoC2/view?usp=sharing) 118 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | // function download(url, callback){ 2 | // console.log("Starting download from the ", url); 3 | // setTimeout(function() { 4 | // console.log("Download complete "); 5 | // const data ="dummy data"; 6 | // callback(data); 7 | // }, 5000) 8 | // } 9 | // function writeFile( data, callback){ 10 | // console.log("Starting writing a file with", data); 11 | // setTimeout(function write(){ 12 | // console.log("complete writing a data in a file"); 13 | // const fileName = "file.txt"; 14 | // callback(fileName); 15 | // }) 16 | // } 17 | // function upload(url, filename, callback){ 18 | // console.log("Starting uploading the data at ", url, "from a file", filename); 19 | // setTimeout(function up(){ 20 | // console.log("Uploading the data completed"); 21 | // callback("SUCCESS"); 22 | // }, 3000); 23 | // } 24 | // download("www.xyz.com", function process(data){ 25 | // console.log("Downloaded data is : ", data); 26 | // writeFile(data, function write(filename){ 27 | // console.log("writed the data in a ", filename); 28 | // upload("www.upload.com", filename, function upload(response){ 29 | // console.log("Uploaded the data with the response ", response); 30 | // }) 31 | // }) 32 | // }) 33 | 34 | 35 | function download(url){ 36 | new Promise(function resolve(){ 37 | console.log("Starting download from the ", url); 38 | setTimeout(function() { 39 | const data = "dummy data"; 40 | resolve(data); 41 | }, 5000) 42 | }) 43 | } 44 | download("www.example.com") 45 | .then(function fulHandler(data){ 46 | console.log("Download complete"); 47 | 48 | }) 49 | --------------------------------------------------------------------------------