├── .vscode
└── settings.json
├── Lectures Codes
├── 22 Promise API's + Interview questions.js
├── 01. Hoisting in Javascript.js
├── 02. Function in Javascript.js
├── 04 Scope and Lexical Enviroment.js
├── 03. Defined and undefined.js
├── 05 Let and Const.js
├── 13 Trust issues with settimeout().js
├── 07 Closures in Javascript.js
├── 18 Using promise.js
├── 16 callback Hell .js
├── 11 Callback Fucntion in javaScript .js
├── 12 Asynchronous Javascript and Event loops .js
├── 21 async await example using fetch.js
├── 10 First Class Functions .js
├── 19 Creating Promise, Chaining and error handling .js
├── 06 Block Scope and Shadowing in Javascript.js
├── 23 this keyword in javascript.js
├── 17 Promises .js
├── 08 Set-Timeout + Closures interview questions.js
├── 14 Functional Programming .js
├── 20 async await .js
├── 09 Crazy JS interview on Closures .js
└── 15 map, filter and reduce .js
├── .gitattributes
├── Notes
├── Readme.md
└── namaste-javascript-notes.pdf
├── index.html
├── Concepts
├── Throtling
│ └── README.md
└── Debouncing
│ └── README.md
├── LICENSE
└── README.md
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "liveServer.settings.port": 5501
3 | }
--------------------------------------------------------------------------------
/Lectures Codes/22 Promise API's + Interview questions.js:
--------------------------------------------------------------------------------
1 | // Adding Questions here
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/Notes/Readme.md:
--------------------------------------------------------------------------------
1 | # Notes
2 | - Pdf notes for Namaste Javascript lecture 👏🏻
3 |
4 | soon... working on it
--------------------------------------------------------------------------------
/Notes/namaste-javascript-notes.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akshadjaiswal/Namaste-JavaScript/HEAD/Notes/namaste-javascript-notes.pdf
--------------------------------------------------------------------------------
/Lectures Codes/01. Hoisting in Javascript.js:
--------------------------------------------------------------------------------
1 | //Hoisting
2 | getname()
3 | console.log(x)
4 | console.log(getname)
5 | var x = 7;
6 | function getname() {
7 | console.log("Namaste Javascript")
8 | }
9 |
10 |
--------------------------------------------------------------------------------
/Lectures Codes/02. Function in Javascript.js:
--------------------------------------------------------------------------------
1 | //Functions
2 | var x = 1;
3 | a();
4 | b();
5 | console.log(x);
6 |
7 | function a() {
8 | var x = 10;
9 | console.log(x);
10 | }
11 | function b() {
12 | var x = 100;
13 | console.log(x);
14 | }
15 |
--------------------------------------------------------------------------------
/Lectures Codes/04 Scope and Lexical Enviroment.js:
--------------------------------------------------------------------------------
1 | //Scope
2 | function a() {
3 | var b = 10;
4 | console.log(b);
5 | c();
6 | function c() {
7 | // console.log(b);
8 | }
9 | }
10 | // console.log(b);//Uncaught reference undefined error b
11 | a();
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Javascript
7 |
8 |
9 |
Namaste 👏🏻 Javascript
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/Lectures Codes/03. Defined and undefined.js:
--------------------------------------------------------------------------------
1 | console.log(x); // undefined
2 | var x = 25;
3 | console.log(x); // 25
4 | console.log(a); // Uncaught ReferenceError: a is not defined
5 |
6 | //checking defined and undefined cases
7 | console.log(a);
8 | var a;
9 | console.log(a);
10 | a = 5;
11 | if (a === undefined) {
12 | console.log("a is undefined")
13 | }
14 | else {
15 | console.log("a is not undefined")
16 | }
17 |
18 | //Holding in javascript
19 | var b;
20 | console.log(b);
21 | b = 10;
22 | console.log(b);
23 | b = "Hello Akshad"
24 | console.log(b);
--------------------------------------------------------------------------------
/Lectures Codes/05 Let and Const.js:
--------------------------------------------------------------------------------
1 | //let in js
2 | console.log(b);//undefined
3 | // console.log(a);//It will throw an error
4 | let a = 10;
5 | // let a=100; Syntax error i.e duplicates are not allowed
6 | console.log(a);
7 | var b = 20;
8 | var b = 200;//But in case of var duplicates are allowed
9 | console.log(b);
10 |
11 | //const in js
12 | let c;//Can initialize later in let
13 | const d = 100;
14 | d = 1000; // Error that you can't change the value of const variable
15 | // const d;
16 | // d=100; initializing later will directly throw an error
17 | c = 10;
18 | console.log(c);
--------------------------------------------------------------------------------
/Lectures Codes/13 Trust issues with settimeout().js:
--------------------------------------------------------------------------------
1 | //Past example of setimeout
2 | console.log("Start")
3 |
4 | setTimeout(function a() {
5 | console.log("Callback")
6 | }, 5000);
7 | console.log("End")
8 |
9 | //Code demonstration for settimeout delay
10 | //It will bloc your main thread for the ten seconds so even settimeout setted for 5 second but it will be printed after the 10sec
11 | let startDate = new Date().getTime();
12 | let endDate = startDate;
13 | while (endDate < startDate + 10000) {
14 | endDate = new Date().getTime();
15 | // console.log(endDate)
16 | }
17 |
18 | console.log("while Expires")
--------------------------------------------------------------------------------
/Lectures Codes/07 Closures in Javascript.js:
--------------------------------------------------------------------------------
1 | // Basic Example of closure
2 | function x() {
3 | var a = 9;
4 | function y() {
5 | console.log(a);
6 | }
7 | // y();
8 | return y;//In javascript you can return the functions
9 | }
10 | var z = x();
11 | console.log(z);//It will return what is present in the function y.
12 | z(); //It will still return the value of a.
13 |
14 | //Corner Cases
15 | function b() {
16 | var e = 99;
17 | function w() {
18 | var c = 9;
19 | function d() {
20 | console.log(c, e);
21 | }
22 | d();
23 | }
24 | w();
25 | }
26 | b();
--------------------------------------------------------------------------------
/Lectures Codes/18 Using promise.js:
--------------------------------------------------------------------------------
1 | //Using promise example
2 | // fetching GitHub profile data
3 | const GITHUB_API = "https://api.github.com/users/akshadjaiswal"
4 |
5 | const user = fetch(GITHUB_API);
6 | console.log(user)
7 |
8 | user.then(function (data) {
9 | console.log(data)
10 | })
11 |
12 | // And this is how Promise is used.
13 | // It guarantees that it could be resolved only once, either it could be `success` or `failure`
14 | /**
15 | A Promise is in one of these states:
16 | pending: initial state, neither fulfilled nor rejected.
17 | fulfilled: meaning that the operation was completed successfully.
18 | rejected: meaning that the operation failed.
19 | */
--------------------------------------------------------------------------------
/Lectures Codes/16 callback Hell .js:
--------------------------------------------------------------------------------
1 | //CallBack in javascript
2 | console.log("Akshad");
3 |
4 | setTimeout(function () {
5 | console.log("Akshad 2");
6 | }, 5000);
7 |
8 | console.log("Jaiswal")
9 |
10 | //Here one call back in to another call back and another callback in another callback and soo on will create the large callback hell
11 | const cart = ["pants", "shoes", "watch"]
12 |
13 | api.createOrder(cart, function () {
14 |
15 | api.makePayment(function () {
16 |
17 | api.showSummary(
18 | function () {
19 | api.updateWallet()
20 | }
21 |
22 | )
23 | })
24 | })
25 |
26 | //The structure will grow horizontally instead of growing vertically which leds to form pyramid of doom of code.
27 |
28 | //Risk of inversion of controll
29 |
30 |
31 |
--------------------------------------------------------------------------------
/Lectures Codes/11 Callback Fucntion in javaScript .js:
--------------------------------------------------------------------------------
1 | //What is callback function in the javascript
2 | setTimeout(function () {
3 | console.log("timer")
4 | }, 5000);
5 | function x(y) {
6 | console.log("x")
7 | y()
8 | }
9 | x(function y() {
10 | console.log("y")
11 | });
12 |
13 | //Event handler and listeners in javascript
14 | document.getElementById("clickMe")
15 | .addEventListener("click", function xyz() {
16 | console.log("button clicked");
17 | })
18 |
19 | //Event handler and listeners in javascript using closures finding the count of click.
20 | function attachEventListener() {
21 | let count = 0;
22 | document.getElementById("clickMe")
23 | .addEventListener("click", function xyz() {
24 | console.log("Button clicked", ++count);
25 | })
26 | }
27 | attachEventListener();
28 |
--------------------------------------------------------------------------------
/Concepts/Throtling/README.md:
--------------------------------------------------------------------------------
1 |
2 | # ⏱️ Throttling
3 |
4 | **Definition:**
5 | Throttling is a technique that limits how often a function can be called over time. It ensures that the function is **executed at most once in a specified time interval**, no matter how many times the event is triggered during that period.
6 |
7 | Unlike debouncing, throttling does **not wait for the event to stop firing**. Instead, it guarantees a fixed rate of execution by ignoring any events that occur within the cooldown window.
8 |
9 | **Key Characteristics:**
10 | - Executes the function at regular intervals.
11 | - Ignores additional triggers until the interval has passed.
12 | - Ensures a consistent, periodic execution rate.
13 |
14 | **Common Use Cases:**
15 | - Scroll event handling.
16 | - Mouse movement tracking.
17 | - Limiting button clicks or API calls per time frame.
--------------------------------------------------------------------------------
/Lectures Codes/12 Asynchronous Javascript and Event loops .js:
--------------------------------------------------------------------------------
1 | //Event loops
2 | //Browser functionality
3 | //DOM APIs
4 | //settimeout
5 | //console
6 | //fetch()
7 |
8 | console.log("Start")
9 | setTimeout(function cb() {
10 | console.log("Callback")
11 | }, 5000);
12 | console.log("End")
13 |
14 | //Example
15 | console.log("Start")
16 | document.getElementById("button")
17 | .addEventListener("click", function cb() {//addeventlistener is the another power given by rhe browser to the engine
18 | console.log("CallBack");
19 | });
20 | console.log("End");
21 |
22 | //Example using fetch
23 | //Example
24 | console.log("Start")
25 | setTimeout(function cbT() {
26 | console.log(" cb setTimeout")
27 | }, 5000);
28 | fetch("https://api.netflix.com")
29 | .then(function cbF() {
30 | console.log("cb Netflix")
31 | })
32 |
33 | console.log("End")
34 |
35 |
--------------------------------------------------------------------------------
/Concepts/Debouncing/README.md:
--------------------------------------------------------------------------------
1 | # 🔁 Debouncing
2 |
3 | Code
4 |
5 | **Definition:**
6 | Debouncing is a programming pattern used to limit the rate at which a function is executed. Specifically, it ensures that the function is only called **after a specified delay has passed since the last time the event was triggered**.
7 |
8 | In practice, every time the event fires, the previously scheduled function execution is canceled and a new one is scheduled. This means the function will **only run after the user has stopped performing the action** for a given period of time.
9 |
10 | **Key Characteristics:**
11 | - Delays execution until after a certain period of inactivity.
12 | - Resets the timer each time the event is triggered.
13 | - Only the **last event** in a series of rapid events is processed.
14 |
15 | **Common Use Cases:**
16 | - Handling input in search boxes.
17 | - Resizing windows.
18 | - Auto-saving form content after typing stops.
19 |
20 | ---
--------------------------------------------------------------------------------
/Lectures Codes/21 async await example using fetch.js:
--------------------------------------------------------------------------------
1 | //Real world example of async await by fetch call by user URL api of github
2 | //"https://api.github.com/users/akshadjaiswal"
3 | const API_URL = "https://api.github.com/users/akshadjaiswal"
4 | // const API_URL = "https://ivalid url"
5 |
6 | async function promiseHandler() {
7 | try { //Error Handling
8 | const data = await fetch(API_URL);
9 | const jsonValue = await data.json();
10 | console.log(jsonValue)
11 | }
12 | catch (err) {
13 | console.log(err);
14 | }
15 | //fetch(API_URL)=Response.json()=>jsonvalue
16 | }
17 | promiseHandler();
18 |
19 | //Other way to handle the error
20 | async function promiseHandler2() {
21 |
22 | const data = await fetch(API_URL);
23 | const jsonValue = await data.json();
24 | console.log(jsonValue)
25 |
26 | //fetch(API_URL)=Response.json()=>jsonvalue
27 | }
28 | promiseHandler2().catch((err) => console.log(err));
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Akshad Jaiswal
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Lectures Codes/10 First Class Functions .js:
--------------------------------------------------------------------------------
1 | a();//It will call the function a
2 | // b();//It will throw an error undefined
3 |
4 | //Function Expression
5 | //also called as function declaration
6 | function a() {
7 | console.log("a called");
8 | }
9 | //a()//you can call it from here
10 |
11 | //Function Declaration
12 | var b = function () {
13 | console.log("b called");
14 | }
15 | b()//you can only call it after the function
16 |
17 | //Anonymous function
18 | // function () {
19 |
20 | // }
21 |
22 | // Named function expression
23 | var b = function xyz() {
24 | console.log(xyz);
25 | }
26 | b()
27 | xyz()//you cannot call this function using xyz due to its scope properties //error undefined
28 |
29 | // Differnce between parameter and arguements
30 | param1 = 10;
31 | param2 = 20;
32 | var b = function (param1, param2) {// the value passed here are called as parameters
33 | console.log("b called");
34 | }
35 | b(param1, param2)// the value passed here are called as arguements
36 |
37 | //First class function
38 | //abilities to use functions as values is called as first class function
39 | var b = function (param1) {
40 | return function xyz() {
41 |
42 | }
43 | }
44 | console.log(b())//we can return function in function as arguement
--------------------------------------------------------------------------------
/Lectures Codes/19 Creating Promise, Chaining and error handling .js:
--------------------------------------------------------------------------------
1 | //Consuming Promise
2 | const cart = ["Shoes", "Watches", "Flags"]
3 |
4 | createOrder(cart)//return orderId
5 | .then(function (orderId) {
6 | console.log(orderId)
7 | return orderId;
8 | })
9 | .then(function (orderId) {
10 | return procedToPayment(orderId);
11 | })
12 | .then(function (paymentInfo) {
13 | console.log(paymentInfo);
14 | })
15 | .catch(function (err) {
16 | console.log(err.message);
17 | })//Handling error and displaying normally in console
18 |
19 | //Creating a promise
20 | //Producer side code
21 | function createOrder(cart) {
22 | const pr = new Promise(function (resolve, reject) {
23 | //validateCart
24 | if (!validateCart(cart)) {
25 | const err = new Error("Cart is not valid")
26 | reject(err);
27 | }
28 | //CreateOrder
29 | const orderId = "12345";
30 | if (orderId) {
31 | setTimeout(function () {
32 | resolve(orderId);
33 | }, 2000)
34 | }
35 | });
36 | return pr;
37 | }
38 | function procedToPayment() {
39 | return new Promise(function (resolve, reject) {
40 | resolve("Payment Successful")
41 | })
42 | }
43 | function validateCart(cart) {
44 | // return true;
45 | return false;
46 | // It will throw an error.//Card is not valid
47 | }
48 |
--------------------------------------------------------------------------------
/Lectures Codes/06 Block Scope and Shadowing in Javascript.js:
--------------------------------------------------------------------------------
1 | //Block
2 | if (true) {
3 | //compound statement
4 | var x = 100;
5 | console.log(x);
6 | }
7 |
8 | //Block Scope
9 | {
10 | var a = 10;
11 | let b = 20;
12 | const c = 30;
13 | console.log(a);
14 | console.log(b);
15 | console.log(c);
16 | }
17 | console.log(a);
18 | // console.log(b); //Uncaught reference error due to the block scope
19 | // console.log(c);
20 |
21 | //Shadowing
22 | var x = 100;//This variable is shadowed by the x varioable present in the block
23 | let y = 200;
24 | const z = 300;
25 | {
26 | var x = 10;//It shadows the variable x outside the block
27 | let y = 20;
28 | const z = 30;
29 | console.log(x);
30 | console.log(y);
31 | console.log(z);
32 | }
33 | console.log(x);
34 | console.log(y);//It will print the y variable present outside the block
35 | console.log(z);//It will print the z variable present outside the block
36 |
37 | //Shadowing for function
38 | var o = 10;
39 | function q() {
40 | var o = 25;
41 | console.log(window.o);//Inside block scope o variable
42 | window.o = 20;
43 | }
44 | q();
45 | console.log(o);//Outside block scope o variable
46 |
47 | //Illegal shadowing
48 | // let w=200;
49 | var w = 12; // but we can shadow var using let
50 | {
51 | // var w=20;//you cannot shadow let using var
52 | let w = 20;// But you can shadow let using let
53 | console.log(w);
54 | }
55 | console.log(w);
--------------------------------------------------------------------------------
/Lectures Codes/23 this keyword in javascript.js:
--------------------------------------------------------------------------------
1 | // "use strict"
2 | // const test = {
3 | // prop: Akshad,
4 | // func: function () {
5 | // return this.prop;
6 | // },
7 | // };
8 |
9 | // console.log(test.func());
10 | // // Expected output: 42
11 |
12 | // const person = {
13 | // name: "Akshad",
14 | // age: 22,
15 | // greet: function () {
16 | // return `Hello ${this.name}, you are ${this.age} years old`;
17 | // },
18 | // };
19 | // console.log(person.greet());
20 |
21 | //this in global space
22 | console.log(this); //globalObject (window)
23 |
24 | //this in inside a function
25 | function x() {
26 | //value depends on strict and non strrict mode
27 | console.log(this);
28 | }
29 | //this in strict mode(this sbstitution)
30 |
31 | //this value depends on how this is called(window)
32 | x();
33 | window.x();
34 |
35 | //this inside a object method
36 | const student = {
37 | name: "Akshad",
38 | printName: function () {
39 | console.log / this;
40 | console.log(this.name);
41 | },
42 | };
43 | student.printName();
44 |
45 | const student2 = {
46 | name: "Aaradhana",
47 | };
48 |
49 | //call apply bind method (sharing method)
50 | student.printName.call(student2);
51 | //apply
52 | //bind
53 |
54 | //this insdie arrow function
55 | const obj = {
56 | a: "akshad",
57 | x: () => {
58 | console.log(this);
59 | },
60 | };
61 | obj.x();
62 | //this inside nested arrow function
63 | const obj2 = {
64 | a: "akshad",
65 | x: function () {
66 | const y = () => {
67 | console.log(this);
68 | };
69 | y();
70 | },
71 | };
72 | obj2.x();
73 | //this inside DOM =====> reference to HTML revised elements
74 | //
75 |
--------------------------------------------------------------------------------
/Lectures Codes/17 Promises .js:
--------------------------------------------------------------------------------
1 | //Promises
2 | const cart = ["Shoes", "Watches", "Flags"]
3 |
4 | // Below two functions are asynchronous and dependent on each other
5 | const orderId = createOrder(cart);
6 | procedToPayment(orderId);
7 |
8 | // with Callback (Before Promise)
9 | // Below here, it is the responsibility of createOrder function to first create the order then call the callback function
10 | createOrder(cart, function () {
11 | procedToPayment(orderId)
12 | });
13 | // Above there is the issue of `Inversion of Control
14 |
15 | const promise = createOrder(cart);//// this promiseR has access to `then`
16 | // {data: undefined}
17 | // Initially it will be undefined so below code won't trigger
18 | // After some time, when execution has finished and promiseRef has the data then automatically the below line will get triggered.
19 |
20 | promise.then(function () {
21 | procedToPayment(orderId)
22 | }); //Here we attaching a function to promise object
23 |
24 | //Promises chaining in javascript
25 | const cart2 = ["Shoes", "Watches", "Flags"]
26 |
27 | const orderId2 = createOrder(cart2);
28 | procedToPayment(orderId2);
29 |
30 | createOrder(cart2, function (orderId2) {
31 | procedToPayment(orderId2, function (paymentInf) {
32 | showOrderSummary(paymentInf, function () {
33 | updateWalletBalance()
34 | })
35 | })
36 | });
37 |
38 | // const promise = createOrder(cart2);
39 | // promise.then(function () {
40 | // procedToPayment(orderId2)
41 | // });
42 |
43 | createOrder(cart2).then(function (orderId2) {
44 | return procedToPayment(orderId2);
45 | })
46 | .then(function (paymentInf) {
47 | return showOrderSummary(paymentInf)
48 | })
49 | .then(function () {
50 | return updateWalletBalance();
51 | })
--------------------------------------------------------------------------------
/Lectures Codes/08 Set-Timeout + Closures interview questions.js:
--------------------------------------------------------------------------------
1 | //SetTImeout Easy question
2 | function x() {
3 | var i = 1;
4 | setTimeout(function () {
5 | console.log(i);
6 | }, 3000);
7 | console.log("Hello from Akshad");//It will first print this console then wait for 3000ms to print the value of i.//JavaScript waits for no one.
8 | }
9 | x();//This set timeout will print the value of i=1 after 3 sec.
10 |
11 | //Print the number 1 to 5 after each seconds using setTimeout
12 | function x() {
13 | //let has block scope and it creates the new copies i after every loop
14 | for (let i = 1; i <= 5; i++) {
15 | setTimeout(function () {
16 | console.log(i);
17 | }, i * 1000);
18 | }
19 | }
20 | x();
21 |
22 | //Print the number 1 to 5 after each seconds using setTimeout by using var
23 | function x() {
24 | //let has block scope and it creates the new copies i after every loop
25 | for (var i = 1; i <= 5; i++) {
26 | function close(x) {
27 | setTimeout(function () {
28 | console.log(x);
29 | }, x * 1000);
30 | }
31 | close(i);//every time we call this function again it will provide the new value of i and now it will work with var
32 | }
33 | console.log("Hello from Akshad ")
34 | }
35 | x();
36 |
37 |
38 | //Print the number 1 to 25 after each seconds using setTimeout by using var
39 | function x() {
40 | //let has block scope and it creates the new copies i after every loop
41 | for (var i = 1; i <= 25; i++) {
42 | function close(x) {
43 | setTimeout(function () {
44 | console.log(x);
45 | }, x * 5000);
46 | }
47 | close(i);//every time we call this function again it will provide the new value of i and now it will work with var
48 | }
49 | console.log("Hello from Akshad ")
50 | }
51 | x();
52 |
--------------------------------------------------------------------------------
/Lectures Codes/14 Functional Programming .js:
--------------------------------------------------------------------------------
1 | //Basic example of higher order function
2 | function x() {
3 | console.log("Akshad");
4 | }
5 | function y(x) {
6 |
7 | }
8 |
9 | //Normally used method to calculate area and circumferenece
10 | const radius = [1, 2, 3, 4, 5];
11 |
12 | const calculateArea = function (radius) {
13 | const output = [];
14 | for (let i = 0; i < radius.length; i++) {
15 | output.push(Math.PI * radius[i] * radius[i]);
16 | }
17 | return output;
18 | }
19 |
20 | console.log(calculateArea(radius));
21 |
22 | //circumference normal
23 | const circumfereneceOfCircle = function (radius) {
24 | const output = [];
25 | for (let i = 0; i < radius.length; i++) {
26 | output.push(2 * Math.PI * radius[i])
27 | }
28 | return output;
29 | }
30 | console.log(circumfereneceOfCircle(radius));
31 |
32 | //for diameter
33 | const diameterOfCircle = function (radius) {
34 | const output = [];
35 | for (let i = 0; i < radius.length; i++) {
36 | output.push(2 * radius[i])
37 | }
38 | return output;
39 | }
40 | console.log(diameterOfCircle(radius));
41 |
42 | ///By functional programming using generic function
43 | const area = function (radius) {
44 | return Math.PI * radius * radius;
45 | }
46 | const circumeference = function (radius) {
47 | return 2 * Math.PI * radius;
48 | }
49 | const diameter = function (radius) {
50 | return 2 * radius;
51 | }
52 |
53 | const calculate = function (radius, logic) {
54 | const output = [];
55 | for (let i = 0; i < radius.length; i++) {
56 | output.push(logic(radius[i]))
57 | }
58 | return output;
59 | }
60 | // console.log(calculate(radius, area));
61 | // console.log(calculate(radius, circumeference));
62 | // console.log(calculate(radius, diameter));
63 |
64 | // Map function // although it is same as above function
65 | console.log(radius.map(area));
66 | console.log(radius.map(circumeference));
67 | console.log(radius.map(diameter));
68 |
69 | //Polyfill for map function
70 | Array.prototype.calculate = function (logic) {
71 | const output = [];
72 | for (let i = 0; i < this.length; i++) {
73 | output.push(logic(this[i]))
74 | }
75 | return output;
76 | }
77 |
78 | // Map function
79 | console.log(radius.calculate(area));
80 |
81 |
82 | console.log(radius.calculate(circumeference));
83 |
84 |
--------------------------------------------------------------------------------
/Lectures Codes/20 async await .js:
--------------------------------------------------------------------------------
1 | // 💡 async function always returns a promise, even if I return a simple string from below function, async keyword will wrap it under Promise and then return.
2 | async function getData() {
3 | return "Namaste JavaScript";
4 | }
5 | const dataPromise = getData();
6 | console.log(dataPromise); // Promise {: 'Namaste JavaScript'}
7 |
8 | //❓How to extract data from above promise? One way is using promise .then
9 | dataPromise.then(res => console.log(res)); // Namaste JavaScript
10 |
11 | function resolveAfter2Seconds() {
12 | return new Promise((resolve) => {
13 | setTimeout(() => {
14 | resolve('resolved');
15 | }, 2000);
16 | });
17 | }
18 |
19 | function resolveAfter10Seconds() {
20 | return new Promise((resolve) => {
21 | setTimeout(() => {
22 | resolve('resolved');
23 | }, 10000);
24 | });
25 | }
26 |
27 | async function asyncCall() {
28 | console.log('calling');
29 | const result = await resolveAfter2Seconds();
30 | console.log(result);
31 | // Expected output: "resolved"
32 | }
33 | asyncCall();
34 |
35 | //Creating a promise
36 | const promise = new Promise((res, rej) => {
37 | res("Promise Resolved")
38 | })
39 |
40 | //async function
41 | async function getData2() {
42 | return promise;//if we return the promise so it will never wrap in another promise
43 | }
44 | const data2 = getData2()
45 |
46 | data2.then(res => console.log(res))
47 | promise.then(res => console.log(res))//Both are same
48 |
49 | //Async and await is use to handle promises
50 | const p = new Promise((resolve, reject) => {
51 | setTimeout(() => {
52 | resolve("Second promise reolved")
53 | }, 10000)
54 | })
55 | const p1 = new Promise((resolve, reject) => {
56 | setTimeout(() => {
57 | resolve("Second promise reolved")
58 | }, 5000)
59 | })
60 |
61 | //handling through async await
62 | //await is a keyword than can only be used in async function
63 | async function promisehandler() {
64 |
65 | console.log("Hello Akshad")
66 | //JS engine is waiting for promisento get resolve
67 | const val = await p;
68 | console.log("Namaste Akshad")
69 | console.log(val);
70 |
71 | const val1 = await p1;
72 | console.log("Namaste Akshad 2")
73 | console.log(val1);
74 | }
75 | promisehandler();
76 |
77 | //Handling nthrough normal function
78 | function getData3() {
79 | p.then(res => (console.log(res)))
80 | }
81 | getData3();
--------------------------------------------------------------------------------
/Lectures Codes/09 Crazy JS interview on Closures .js:
--------------------------------------------------------------------------------
1 | //Example on closure
2 | function outer() {
3 | var a = 10;
4 | function inner() {
5 | console.log(a);
6 | }
7 | return inner;
8 | }
9 | outer()();//It still remembers the value of a variable.
10 |
11 | //Changing postion of variable
12 | function outer() {
13 | // var a=10;
14 | function inner() {
15 | console.log(a);
16 | }
17 | var a = 10;//Even if we morve the position of variable declartion it is still closure
18 | return inner;
19 | }
20 | outer()();
21 |
22 | //Changing var to let
23 | function outer() {
24 | // var a=10;
25 | function inner() {
26 | console.log(a);
27 | }
28 | let a = 10;//Even if we change the var to let it is still closure
29 | return inner;
30 | }
31 | outer()();
32 |
33 | //Pass an paramerter in outer function
34 | function outer(b) {
35 | function inner() {
36 | console.log(a, b);
37 | }
38 | let a = 10;
39 | return inner;
40 | }
41 | var close = outer("Hello from Akshad");
42 | close();
43 |
44 | //Relation of scope chain and closure
45 | function outest() {
46 | function outer(b) {
47 | var c = 20;
48 | function inner() {
49 | console.log(a, b, c);
50 | }
51 | let a = 10;
52 | return inner;
53 | }
54 | return outer;
55 | }
56 | var close = outest()("Hello from Akshad");
57 | close();
58 |
59 | //Conflicting name of global variable let in js
60 | function outest() {
61 | function outer(b) {
62 | var c = 20;
63 | function inner() {
64 | console.log(a, b, c);
65 | }
66 | let a = 10;
67 | return inner;
68 | }
69 | return outer;
70 | }
71 | let a = 100;//but it will still print the value of a present in the function scope.
72 | var close = outest()("Hello from Akshad");
73 | close();
74 |
75 | //Example of data privacy using closures
76 | function counter() {
77 | count = 0;
78 | return function incrmentCounter() {
79 | count++;
80 | console.log(count);
81 | }
82 | }
83 | //console.log(count);// No one can access this count outside the closure.it will throw error.
84 | var counter1 = counter();
85 | counter1();
86 | counter1();
87 | counter1();
88 | counter1();
89 |
90 | //Function Constructor in javascript using closures
91 | function Counter() {
92 | count = 0;
93 | this.incrementCounter = function () {
94 | count++;
95 | console.log(count);
96 | }
97 | this.decrementCounter = function () {
98 | count--;
99 | console.log(count);
100 | }
101 | }
102 | var counter1 = new Counter();
103 | counter1.incrementCounter()
104 | counter1.incrementCounter()
105 | counter1.decrementCounter()
106 | counter1.decrementCounter()
107 | counter1.incrementCounter()
108 |
109 |
--------------------------------------------------------------------------------
/Lectures Codes/15 map, filter and reduce .js:
--------------------------------------------------------------------------------
1 | //Map function //basically use to transform an array
2 | const arr = [5, 1, 8, 7, 4];
3 | //Double- [10,2,16,14,8]
4 | function double(x) {
5 | return x * 2;
6 | }
7 |
8 | //Triple the array
9 | function triple(x) {
10 | return x * 3
11 | }
12 |
13 | //Binary values of the array
14 | function binary(x) {
15 | return x.toString(2);
16 | }
17 |
18 | const output = arr.map(double);
19 | const output2 = arr.map(triple);
20 | const output3 = arr.map(binary);
21 | console.log(output);
22 | console.log(output2);
23 | console.log(output3);
24 |
25 | //Filter is use to filter the value in arrays according to some specific logic
26 |
27 | //Filter odd values from array
28 | function isOdd(x) {
29 | return x % 2;
30 | }
31 | function isEven(x) {
32 | return x % 2 === 0;
33 | }
34 | function greaterThanFour(x) {
35 | return x > 4;
36 | }
37 | const odd = arr.filter(isOdd);
38 | const even = arr.filter(isEven);
39 | const greater = arr.filter(greaterThanFour);
40 | console.log(odd);
41 | console.log(even);
42 | console.log(greater);
43 |
44 | //Reduce - As the name reduce it actually does not reduce anything
45 |
46 | //Sum or max
47 | // Non reduce method
48 |
49 | function sumOfArray(x) {
50 | let sum = 0;
51 | for (let i = 0; i < arr.length; i++) {
52 | sum = sum + arr[i];
53 | }
54 | return sum;
55 | }
56 | console.log(sumOfArray(arr))
57 |
58 | //By using reduce
59 | const output4 = arr.reduce(function (acc, curr) { //accumulator and current
60 | acc = acc + curr;//acc is like sum and curr like arr[i]
61 | return acc;
62 | }, 0)
63 | console.log(output4);
64 |
65 | //Max of array using normal function
66 | function maxOfArray(x) {
67 | let max = 0;
68 | for (let i = 0; i < arr.length; i++) {
69 | if (max < arr[i]) {
70 | max = arr[i];
71 | }
72 | }
73 | return max;
74 | }
75 | console.log(maxOfArray(arr));
76 |
77 | //Max of array using reduce
78 | const output5 = arr.reduce(function (acc, curr) {
79 | if (acc < curr) {
80 | acc = curr;
81 | }
82 | return acc;
83 | }, 0)
84 | console.log(output5)
85 |
86 | //Example of Map
87 | const users = [
88 | { firstName: "Akshad", lastName: "Jaiswal", age: 21 },
89 | { firstName: "Jarad", lastName: "Higgins", age: 22 },
90 | { firstName: "Arijit", lastName: "Singh", age: 33 },
91 | { firstName: "Tupac", lastName: "Shakur", age: 25 }
92 | ]
93 |
94 | //List of full names
95 | const fullname = users.map((x) => x.firstName + " " + x.lastName)
96 | console.log(fullname);
97 |
98 | // reduce example for age
99 | const output6 = users.reduce(function (acc, curr) {
100 | if (acc[curr.age]) {
101 | acc[curr.age] = ++acc[curr.age];
102 | } else {
103 | acc[curr.age] = 1;
104 | }
105 | return acc;
106 | }, {})
107 | console.log(output6);
108 |
109 | //first name of user whos age is les than 30
110 | const output7 = users.filter((x) => x.age < 30).map((x) => x.firstName)
111 |
112 | console.log(output7)
113 |
114 | //first name of user whos age is les than 30 using reduce only
115 | const output8 = users.reduce(function (acc, curr) {
116 | if (curr.age < 30) {
117 | acc.push(curr.firstName)
118 | }
119 | return acc
120 | }, [])
121 | console.log(output8)
122 |
123 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Namaste JavaScript Notes (Theory + Code)🎯
2 |
3 | This repository is my attempt at sharing JavaScript knowledge with everyone, even those who might not have the time to go through all the videos. I also use this repo for quick reference to JavaScript concepts when necessary.
4 |
5 | ## ❓ What it is?
6 |
7 | > This repo maintains my version of JavaScript notes which I learned from the famous [Namaste JavaScript YouTube Series](https://www.youtube.com/playlist?list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP) by Akshay Saini.
8 |
9 | ## 📝 Resource Used
10 |
11 | - [Namaste 🙏 JavaScript course](https://www.youtube.com/playlist?list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP) by [Akshay Saini](https://github.com/akshaymarch7)
12 |
13 | ### [More Learning Resources](#more-learning-resources)
14 |
15 | - [React](https://github.com/akshadjaiswal/React)
16 | - [NodeJs](https://github.com/akshadjaiswal/Namaste-Nodejs)
17 |
18 | ---
19 |
20 | # Season 01
21 |
22 | ## Episode 1: Execution Context
23 |
24 | #### Everything in JS happens inside the execution context.
25 |
26 | Assume the execution context to be a big box where everything takes place. It has 2 components in it:
27 | - **Memory:** The place where all the variables and functions are stored as (key: value) pairs. Memory component is also known as the _variable environment_.
28 | - **Code:** The place where code is executed one line at a time. Code component is also known as the _Thread of Execution_.
29 |
30 | ### JS is a synchronous single-threaded language.
31 |
32 | ## Episode 2: Execution & Call Stack
33 |
34 | When a JS program runs, a global execution context is created.
35 | - The execution context is created in two phases.
36 | - Memory creation phase - JS will allocate memory to variables and functions.
37 | - Code execution phase.
38 |
39 | ## Episode 3: [Hoisting](https://github.com/akshadjaiswal/Namaste-JavaScript/blob/main/Lectures%20Codes/01.%20Hoisting%20in%20Javascript.js)
40 |
41 | - **Hoisting** is a concept which enables us to extract values of variables and functions even before initializing/assigning value without getting an error. This happens due to the 1st phase (memory creation phase) of the Execution Context.
42 |
43 | ## Episode 4: [Functions and Variable Environments](https://github.com/akshadjaiswal/Namaste-JavaScript/blob/main/Lectures%20Codes/02.%20Function%20in%20Javascript.js)
44 |
45 | ### Code Flow in terms of Execution Context
46 |
47 | - The Global Execution Context (GEC) is created (the big box with Memory and Code subparts). Also, GEC is pushed into the Call Stack.
48 |
49 | ## Episode 5: Shortest JS Program, Window, and `this` keyword
50 |
51 | - The shortest JS program is an empty file because even then, the JS engine does a lot of things. As always, even in this case, it creates the GEC (Global Execution Context) which has memory space and the execution context.
52 | - The JS engine creates something known as 'window'. It is an object created in the global space.
53 | - The JS engine also creates a `this` keyword, which points to the window object at the global level. At the global level, this === window.
54 | - If we create any variable in the global scope, then the variables get attached to the global object.
55 |
56 | ## Episode 6: [Undefined vs Not Defined](https://github.com/akshadjaiswal/Namaste-JavaScript/blob/main/Lectures%20Codes/03.%20Defined%20and%20undefined.js)
57 |
58 | - In the first phase (memory allocation), JS assigns each variable a placeholder called `undefined`.
59 | - `undefined` is when memory is allocated for the variable, but no value is assigned yet.
60 | - If an object/variable is not even declared/found in the memory allocation phase, and tried to access it then it is `Not defined`.
61 | - `Not Defined` !== `Undefined`
62 |
63 | ### When a variable is declared but not assigned value, its current value is `undefined`. But when the variable itself is not declared but called in code, then it is `not defined`.
64 |
65 | ## Episode 7: [Scope and Lexical Environment](https://github.com/akshadjaiswal/Namaste-JavaScript/blob/main/Lectures%20Codes/04%20Scope%20and%20Lexical%20Enviroment.js)
66 |
67 | - Scope in JavaScript is directly related to Lexical Environment.
68 | - Lexical Environment = local memory + lexical env of its parent.
69 | - Whenever an Execution Context is created, a Lexical environment (LE) is also created and is referenced in the local Execution Context (in memory space).
70 | - The process of going one by one to the parent and checking for values is called scope chain or Lexical environment chain.
71 |
72 | ## Episode 8: [let, const, temporal dead zone, types of errors](https://github.com/akshadjaiswal/Namaste-JavaScript/blob/main/Lectures%20Codes/05%20Let%20and%20Const.js)
73 |
74 | - `let` and `const` declarations are hoisted but differently from `var`.
75 | - Temporal Dead Zone: Time since when the `let` variable was hoisted until it is initialized with some value.
76 | - Reference Error is thrown when variables are in the temporal dead zone.
77 | - Syntax Error doesn't even let us run a single line of code.
78 | - `let` is a stricter version of `var`. `const` is even stricter than `let`.
79 | - Types of Error: Syntax, Reference, and Type.
80 | - Uncaught ReferenceError: x is not defined at ...
81 | - Uncaught ReferenceError: cannot access 'a' before initialization
82 | - Uncaught SyntaxError: Identifier 'a' has already been declared
83 | - Uncaught SyntaxError: Missing initializer in const declaration
84 | - Uncaught TypeError: Assignment to constant variable
85 |
86 | ## Episode 9: [Block Scope and Shadowing](https://github.com/akshadjaiswal/Namaste-JavaScript/blob/main/Lectures%20Codes/06%20Block%20Scope%20and%20Shadowing%20in%20Javascript.js)
87 |
88 | ### What is a Block?
89 |
90 | - Block aka compound statement is used to group JS statements together into one group. We group them within `{...}`
91 |
92 | ### What is Shadowing?
93 |
94 | - If one has the same named variable outside the block, the variable inside the block shadows the outside variable. This happens only for `var`.
95 |
96 | ### What is Illegal Shadowing?
97 |
98 | - We cannot shadow `let` with `var`. But it is valid to shadow a `let` using a `let`. However, we can shadow `var` with `let`.
99 | - All scope rules that work in function are the same in arrow functions too.
100 |
101 | ## Episode 10: [Closures in JS](https://github.com/akshadjaiswal/Namaste-JavaScript/blob/main/Lectures%20Codes/07%20Closures%20in%20Javascript.js)
102 |
103 | - Function bundled along with its lexical scope is a closure.
104 | - JavaScript has a lexical scope environment. If a function needs to access a variable, it first goes to its local memory. When it does not find it there, it goes to the memory of its lexical parent.
105 | - A closure is a function that has access to its outer function scope even after the function has returned.
106 | - Advantages of Closure:
107 | - Module Design Pattern
108 | - Currying
109 | - Memoize
110 | - Data hiding and encapsulation
111 | - setTimeouts etc.
112 | - Disadvantages of Closure:
113 | - Over consumption of memory
114 | - Memory Leak
115 | - Freeze browser
116 |
117 | ## Episode 11: [setTimeout + Closures Interview Question](https://github.com/akshadjaiswal/Namaste-JavaScript/blob/main/Lectures%20Codes/08%20Set-Timeout%20%2B%20Closures%20interview%20questions.js)
118 |
119 | - Time, tide, and JavaScript wait for none.
120 |
121 | ## Episode 12: [JS interview questions](https://github.com/akshadjaiswal/Namaste-JavaScript/blob/main/Lectures%20Codes/09%20Crazy%20JS%20interview%20on%20Closures%20.js)
122 |
123 | - Q1: What is Closure in Javascript?
124 | - Ans: A function along with a reference to its outer environment together forms a closure.
125 | - Q2: Will the below code still form a closure?
126 | - Yes, because the inner function forms a closure with its outer environment so sequence doesn't matter.
127 | - Q3: Changing `var` to `let`, will it make any difference?
128 | - Q4: Will the inner function have access to the outer function argument?
129 | - Q5: In the below code, will the inner form closure with the outest?
130 | - Q6: Output of the below code and explanation?
131 | - Q7: Advantage of Closure?
132 | - Q8: Discuss more on Data hiding and encapsulation?
133 | - Q9: Disadvantage of closure?
134 | - Overconsumption of memory when using closure as those closed-over variables are not garbage collected till the program expires. So when creating many closures, more memory is accumulated and this can create memory leaks if not handled.
135 |
136 | ## Episode 13: [First class and Anonymous functions](https://github.com/akshadjaiswal/Namaste-JavaScript/blob/main/Lectures%20Codes/10%20First%20Class%20Functions%20.js)
137 |
138 | ### Functions are the heart ♥ of JavaScript.
139 |
140 | - Q: What is Function statement?
141 | - Q: What is Function Expression?
142 | - Q: Difference between function statement and expression
143 | - The major difference between these two lies in Hoisting.
144 | - Q: What is Function Declaration?
145 | - Another name for a function statement.
146 | - Q: What is Anonymous Function?
147 | - A function without a name.
148 | - Q: What is Named Function Expression?
149 | - Same as Function Expression but the function has a name instead of being anonymous
150 | - Q: Parameters vs Arguments?
151 | - Q: What is First Class Function aka First Class Citizens?
152 | - We can pass functions inside a function as arguments and/or return a function (HOF). These abilities are altogether known as First class function.
153 |
154 | ## Episode 14: [Callbacks and Event Listeners](https://github.com/akshadjaiswal/Namaste-JavaScript/blob/main/Lectures%20Codes/11%20Callback%20Fucntion%20in%20javaScript%20.js)
155 |
156 | ### Callback Functions
157 |
158 | - Functions are first-class citizens i.e., take a function A and pass it to another function B. Here, A is a callback function. This callback function gives us access to the whole Asynchronous world in the Synchronous world.
159 | - JS is a synchronous and single-threaded language. But due to callbacks, we can do async things in JS.
160 |
161 | ### Event Listener
162 |
163 | ### Garbage Collection and removeEventListeners
164 |
165 | - Event listeners are heavy as they form closures. So even when the call stack is empty, EventListener won't free up memory allocated to count as it doesn't know when it may need count again. So we remove event listeners when we don't need them (garbage collected) onClick, onHover, onScroll all in a page can slow it down heavily.
166 |
167 | ## Episode 15: [Asynchronous JS and Event Loops](https://github.com/akshadjaiswal/Namaste-JavaScript/blob/main/Lectures%20Codes/12%20Asynchronous%20Javascript%20and%20Event%20loops%20.js)
168 |
169 | ### Note: Call stack will execute any execution context which enters it. Time, tide, and JS wait for none.
170 |
171 | - Browser has a JS Engine which has Call Stack which has Global execution context, local execution context etc.
172 | - But the browser has many other superpowers - Local storage space, Timer, place to enter URL, Bluetooth access, Geolocation access, and so on.
173 | - Now JS needs some way to connect the call stack with all these superpowers. This is done using Web APIs
174 |
175 | ### WebAPIs
176 |
177 | - None of the below are part of Javascript! These are extra superpowers that the browser has. Browser gives access to JS callstack to use these powers.
178 | - setTimeout(), DOM APIs, fetch(), localstorage, console (yes, even console.log is not JS!!), location and so many more.
179 | - setTimeout(): Timer function
180 | - DOM APIs: eg. `Document.xxx` ; Used to access HTML DOM tree. (Document Object Manipulation)
181 | - fetch(): Used to make connection with external servers eg. Netflix servers etc.
182 | - We get all these inside call stack through the global object ie. `window`
183 | - Use the window keyword like: `window.setTimeout()`, `window.localstorage`, `window.console.log()` to log something inside the console.
184 | - As `window` is a global obj, and all the above functions are present in the global object, we don't explicitly write `window` but it is implied.
185 |
186 | ### Need of callback queue?
187 |
188 | - Suppose a user clicks the button 6 times. So 6 cb() are put inside the callback queue. The event loop sees if the call stack is empty/has space and whether the callback queue is not empty(6 elements here). Elements of the callback queue popped off, put in call stack, executed, and then popped off from the call stack.
189 |
190 | ### What enters the Microtask Queue?
191 |
192 | - All the callback functions that come through promises go in the microtask Queue.
193 | - Mutation Observer: Keeps on checking whether there is a mutation in the DOM tree or not, and if there, then it executes some callback function.
194 | - Callback functions that come through promises and mutation observer go inside Microtask Queue.
195 | - All the rest goes inside Callback Queue aka. Task Queue.
196 | - If the task in the microtask Queue keeps creating new tasks in the queue, the element in the callback queue never gets a chance to run. This is called starvation.
197 |
198 | ### Some Important Questions
199 |
200 | - **When does the event loop actually start?**
201 | - Event loop, as the name suggests, is a single-thread, loop that is almost infinite. It's always running and doing its job.
202 | - **Are only asynchronous web API callbacks are registered in the web API environment?**
203 | - YES, the synchronous callback functions like what we pass inside map, filter, and reduce aren't registered in the Web API environment. It's just those async callback functions which go through all this.
204 | - **Does the web API environment store only the callback function and push the same callback to the queue/microtask queue?**
205 | - Yes, the callback functions are stored, and a reference is scheduled in the queues. Moreover, in the case of event listeners(for example click handlers), the original callbacks stay in the web API environment forever, that's why it's advised to explicitly remove the listeners when not in use so that the garbage collector does its job.
206 | - **How does it matter if we delay for setTimeout would be 0ms. Then the callback will move to queue without any wait?**
207 | - No, there are trust issues with setTimeout(). The callback function needs to wait until the Call Stack is empty. So the 0 ms callback might have to wait for 100ms also if the stack is busy.
208 |
209 | ## Episode 16: JS Engine Exposed Google's V8 architecture
210 |
211 | ### JS runs literally everywhere from smartwatches to robots to browsers because of the JavaScript Runtime Environment (JRE)
212 |
213 | - JRE consists of a JS Engine (heart of JRE), a set of APIs to connect with the outside environment, event loop, Callback queue, Microtask queue etc.
214 | - JRE is a container that can run JS code.
215 | - ECMAScript is a governing body of JS. It has a set of rules followed by all JS engines like Chakra(Edge), Spidermonkey(Firefox), v8(Chrome)
216 | - JS Engine is **not a machine**. It's software written in low-level languages (eg. C++) that takes in high-level code in JS and spits out low-level machine code.
217 |
218 | ### In all languages, code is compiled either with an **interpreter** or with a **compiler**. JS used to have only an interpreter in old times, but now has **both** to compile JS code.
219 |
220 | - Interpreter: Takes code and executes line by line. Has no idea what will happen in the next line. Very fast.
221 | - Compiler: Code is compiled and an optimized version of the same code is formed, and then executed. More efficient.
222 |
223 | ### Code inside JSE passes through 3 steps: **Parsing, Compilation, and Execution**
224 |
225 | 1. **Parsing**: Code is broken down into tokens. In `let a = 7` -> `let`, `a`, `=`, `7` are all tokens. Also, we have a **syntax parser** that takes code and converts it into an **AST (Abstract Syntax Tree)** which is a JSON with all key values like type, start, end, body etc.
226 | 2. **Compilation**: JS has something called **Just-in-time(JIT) Compilation - uses both interpreter & compiler**. Also, compilation and execution both go hand in hand. The AST from the previous step goes to the interpreter which converts high-level code to byte code and moves to execution. While interpreting, the compiler also works hand in hand to compile and form optimized code during runtime.
227 | 3. **Execution**: Needs 2 components ie. Memory heap(place where all memory is stored) and Call Stack(same call stack from previous episodes). There is also a _garbage collector._ It uses an algorithm called **Mark and Sweep**.
228 |
229 | Companies use different JS engines and each tries to make theirs the best.
230 |
231 | - v8 of Google has an Interpreter called _Ignition_, a compiler called _Turbo Fan_, and a garbage collector called _Orinoco_.
232 |
233 | ## Episode 17: [Trust issues with setTimeout()](https://github.com/akshadjaiswal/Namaste-JavaScript/blob/main/Lectures%20Codes/13%20Trust%20issues%20with%20settimeout().js)
234 |
235 | ### The First rule of JavaScript: Do not block the main thread (as JS is a single-threaded (only 1 call stack language)).
236 |
237 | - In the code example, we are blocking the main thread. Observe the Question and Output.
238 | - setTimeout guarantees that it will take at least the given timer to execute the code.
239 | - JS is a synchronous single-threaded language. With just 1 thread it runs all pieces of code. It becomes kind of an interpreter language and runs code very fast inside the browser (no need to wait for code to be compiled) (JIT - Just in time compilation). And there are still ways to do async operations as well.
240 |
241 | ## Episode 18: [Higher Order Functions ft. Functional Programming](https://github.com/akshadjaiswal/Namaste-JavaScript/blob/main/Lectures%20Codes/14%20Functional%20Programming%20.js)
242 |
243 | ### Q: What is a Higher Order Function?
244 |
245 | - Ans: Higher-order functions are regular functions that take other functions as arguments or return functions as their results.
246 |
247 | ### More explanations in the code file with examples and demonstration.
248 |
249 | ## Episode 19: [map, filter, and reduce](https://github.com/akshadjaiswal/Namaste-JavaScript/blob/main
250 | ### map, filter & reducer are Higher Order Functions.
251 | - Map function
252 | - It is basically used to transform a array. The map() method creates a new array with the results of calling afunction for every array element.
253 | - So basically map function maps each and every value and transforming it based on given condition.
254 | - Filter function
255 | - Filter function is basically used to filter the value inside an array. The arr.filter() method is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument method.
256 | - Filter function creates an array and store only those values which evaluates to true.
257 | - Reduce function
258 | - It is a function which take all the values of array and gives a single output of it. It reduces the array to give a single output.
259 |
260 | # Season 02:-
261 | # Episode 01 : [Callback Hell.](https://github.com/akshadjaiswal/Namaste-JavaScript/blob/main/Lectures%20Codes/16%20callback%20Hell%20.js)
262 | ## There are 2 Parts of Callback:
263 | ### 1. Good Part of callback
264 | - Callback are super important while writing asynchronous code in JS.
265 | ### 2. Bad Part of Callback
266 | - Using callback we can face issue:
267 | - 1 Callback hell
268 | - When a function is passed as an argument to another function, it becomes a callback function. This process continues and there are many callbacks inside another's Callback function.
269 | - This grows the code horizontally instead of vertically. That mechanism is known as callback hell.
270 |
271 | - 2 Inversion of control
272 | - The callback function is passed to another callback, this way we lose the control of our code. We don't know what is happening behind the scene and the program becomes very difficult to maintain. That process is called inversion of control.
273 |
274 | # Episode 02 : [Promises.](https://github.com/akshadjaiswal/Namaste-JavaScript/blob/main/Lectures%20Codes/17%20Promises%20.js)
275 | ### Promises are used to handle async operations in JavaScript.
276 | ### We will discuss with code example that how things used to work before Promises and then how it works after Promises
277 | Interview Guide
278 | - What is Promise?
279 | - Promise object is a placeholder for certain period of time until we receive value from asynchronous operation.
280 | - A container for a future value.
281 | - A Promise is an object representing the eventual completion or failure of an asynchronous operation.
282 | - We are now done solving one issue of callback i.e. Inversion of Control
283 |
284 | # Episode 03 : [Creating promise, Chainning and Error Handling](https://github.com/akshadjaiswal/Namaste-JavaScript/blob/main/Lectures%20Codes/17%20Promises%20.js)
285 |
286 | > Promises are used to handle async operations in JavaScript.
287 | - Now, Let's understand the concept of Promise Chaining
288 | - for this we will assume after createOrder we have to invoke proceedToPayment
289 | - In promise chaining, whatever is returned from first .then become data for next .then and so on...
290 | - At any point of promise chaining, if promise is rejected, the execution will fallback to .catch and others promise won't run.
291 | - Q: What if we want to continue execution even if any of my promise is failing, how to achieve this?
292 | - By placing the .catch block at some level after which we are not concerned with failure.
293 | - There could be multiple .catch too.
294 |
295 | # Episode 04 - [async await](https://github.com/akshadjaiswal/Namaste-JavaScript/blob/main/Lectures%20Codes/20%20async%20await%20%20.js)
296 | - Topics Covered
297 | - What is async?
298 | - What is await?
299 | - How async await works behind the scenes?
300 | - Example of using async/await
301 | - Error Handling
302 | - Interviews
303 | - Async await vs Promise.then/.catch
304 | - Q: What is async?
305 | - A: Async is a keyword that is used before a function to create a async function.
306 | - Q: Question is Is program actually waiting or what is happening behind the scene?
307 | - A: As we know, Time, Tide and JS wait for none. And it's true. Over here it appears that JS engine is waiting but JS engine is not waiting over here. It has not occupied the call stack if that would have been the case our page may have got frozen. So JS engine is not waiting. So if it is not waiting then what it is doing behind the scene? Let's understand with attached [code](https://github.com/akshadjaiswal/Namaste-JavaScript/blob/main/Lectures%20Codes/20%20async%20await%20%20.js)
308 | - Error Handling
309 | - While we were using normal Promise we were using .catch to handle error, now in async-await we would be using try-catch block to handle error.
310 | - Async await vs Promise.then/.catch
311 | - What one should use? async-await is just a syntactic sugar around promise. Behind the scene async-await is just promise. So both are same, it's just async-await is new way of writing code. async-await solves few of the short-coming of Promise like Promise Chaining. async-await also increases the readability. So sort of it is always advisable to use async-await.
312 | - Fetch Call and Error handling
313 | - [Example of using of fetch api call using async await and error handling](https://github.com/akshadjaiswal/Namaste-JavaScript/blob/main/Lectures%20Codes/21%20async%20await%20example%20using%20fetch.js).
314 |
315 | # Episode 04 : [Promise APIs + Interview Questions]()
316 | - Questions here soon 🔜
317 |
318 | # Episdoe 05 - [this keyword in Javascript](https://github.com/akshadjaiswal/Namaste-JavaScript/blob/main/Lectures%20Codes/23%20this%20keyword%20in%20javascript.js)
319 |
320 | - JavaScript's "this" keyword can be confusing for many and behaves differently in various scenarios.
321 |
322 | - In JavaScript, this keyword refers to the current context or scope within which code is executing. Its value is determined by how a function is called, and it can dynamically change depending on the invocation context.
323 |
324 | - In the global space, the value of "this" is the global object, which can vary depending on the JavaScript runtime environment (e.g., window in browsers, Global in Node.js).
325 |
326 | - Inside a function, the value of "this" can be undefined in strict mode or the global object in non-strict mode.
327 |
328 | - JavaScript uses a mechanism called "this substitution," where "this" is replaced with the global object when it's undefined or null in non-strict mode.
329 |
330 | - Inside an object's method, "this" refers to the object itself where the method is called.
331 |
332 | - "call," "apply," and "bind" are important functions used to manipulate the value of "this" when calling methods and sharing them between objects.
333 |
334 | - It's essential to understand "call," "apply," and "bind" to effectively control the value of "this" in JavaScript methods.
335 |
336 | - In global space, the 'this' keyword refers to the global object (e.g., 'window' in the browser).
337 |
338 | - In strict mode, 'this' inside a function is undefined; in non-strict mode, it refers to the global object.
339 |
340 | - Understanding "this" substitution: When 'this' is undefined or null inside a function, it becomes the global object.
341 |
342 | - Inside an object's method, 'this' refers to the object itself.
343 |
344 | - The 'call' method can be used to invoke a function with a specific 'this' context.
345 |
346 | - Arrow functions do not have their own 'this' binding and take the value of the enclosing lexical context.
347 |
348 | - In the context of DOM elements, 'this' refers to the specific HTML element being
349 |
350 | ## More Learning Resources
351 |
352 | Explore my additional repositories to deepen your understanding of related topics in the JavaScript ecosystem:
353 |
354 | - [Namaste NodeJS](https://github.com/akshadjaiswal/Namaste-Nodejs): A repository focused on learning Node.js concepts, from basics to advanced server-side programming.
355 | - [Namaste React](https://github.com/akshadjaiswal/Namaste-React): A repository dedicated to mastering React.js, covering foundational and advanced aspects of building interactive UIs.
356 |
357 | ---
358 | ## 🤝 Contribution Guidelines
359 |
360 | - Please create an issue with your suggestion.
361 | - If you have notes of your own, and are interested in contributing to this repo, hit a PR ! I'll review it and add it immediately 🤓.
362 |
363 | ## ✨ Show your support
364 |
365 | Give a ⭐️ if this project helped you and try to contribute and share with people's
366 | Happy learning and coding!
367 |
368 | ---
369 |
370 |