18 |
19 |
44 |
45 |
--------------------------------------------------------------------------------
/src/07_projects/2-BMICalculator/chaiaurcode.js:
--------------------------------------------------------------------------------
1 | // we will get the form
2 | const form = document.querySelector("form");
3 |
4 | //form submition will be post, so we need to stop the submission
5 | //on submit click, get the values of height and weight
6 | form.addEventListener("submit", function (e) {
7 | //to stop the default submission
8 | e.preventDefault();
9 |
10 | //step to get the value of input
11 | //parseInt: convert the string value into int
12 | const height = parseInt(document.querySelector("#height").value);
13 | const weight = parseInt(document.querySelector("#weight").value);
14 | const results = document.querySelector("#results");
15 |
16 | //apply some checks, if those checks are correct than add the values
17 | //height should not be empty
18 | if (height === "" || height < 0 || isNaN(height)) {
19 | results.innerHTML = `Please give a valid height ${height}`;
20 | // height.innerHTML = '';
21 | // weight.innerHTML = '';
22 | } else if (weight === "" || weight < 0 || isNaN(weight)) {
23 | results.innerHTML = `Please give a valid weight ${weight}`;
24 | } else {
25 | //if everything is fine, then calculate the BMI
26 | const bmi = (weight / ((height * height) / 10000)).toFixed(2);
27 |
28 | //Show the results
29 |
30 | //check the result, whether it is under weight or over weight
31 | if (bmi < 18.6) {
32 | results.innerHTML = ` You have under weight of ${bmi}`;
33 | } else if (bmi > 18.6 && bmi < 24.6) {
34 | results.innerHTML = ` You have Normal Range of ${bmi}`;
35 | } else if (bmi > 24.6) {
36 | results.innerHTML = ` You have over weight of ${bmi}`;
37 | }
38 | }
39 | });
40 |
--------------------------------------------------------------------------------
/src/03_Basics/01_functions.js:
--------------------------------------------------------------------------------
1 | function sayMyName() {
2 | console.log("H");
3 | console.log("I");
4 | console.log("T");
5 | console.log("E");
6 | console.log("S");
7 | console.log("H");
8 | }
9 |
10 | // sayMyName();
11 |
12 | // function addTwoNumbers(number1, number2){
13 | // console.log( number1 + number2 );
14 | // }
15 |
16 | function addTwoNumbers(number1, number2) {
17 | // let result = number1 + number2
18 | // return result;
19 |
20 | return number1 + number2;
21 | }
22 |
23 | const result = addTwoNumbers(3, 4);
24 | // console.log("Result ", result);
25 |
26 | function loginUserMessage(username = "sam") {
27 | if (!username) {
28 | console.log("Please enter username");
29 | return;
30 | }
31 | return `${username} just logged in`;
32 | }
33 | // console.log(loginUserMessage("hitesh"))
34 | // console.log(loginUserMessage())
35 |
36 | //------------ function with objects ------------------
37 |
38 | function calculatetCartPrice(val1, val2, ...num1) {
39 | return num1;
40 | }
41 |
42 | // console.log(calculatetCartPrice(200, 400, 500, 2000));
43 |
44 | const user = {
45 | username: "hitesh",
46 | price: 199
47 | };
48 |
49 | function handleObject(anyObject) {
50 | console.log(
51 | `Username is ${anyObject["username"]} and price is ${anyObject["price"]}`
52 | );
53 | }
54 |
55 | // handleObject(user);
56 | // we can pass the object directly
57 |
58 | handleObject({
59 | username: "sam",
60 | price: 399
61 | });
62 |
63 | //--------- function with array -------------
64 |
65 | const myNewArray = [200, 400, 100, 600];
66 | function returnSecondValue(gerArray) {
67 | return gerArray[1];
68 | }
69 |
70 | // console.log(returnSecondValue(myNewArray));
71 | console.log(returnSecondValue([100, 200, 300]));
72 |
--------------------------------------------------------------------------------
/src/10_classes_and_oop/3-Prototype.js:
--------------------------------------------------------------------------------
1 | let myName = "hitesh ";
2 | let myChannel = "chai ";
3 |
4 | // console.log(myName.trim().length);
5 | // console.log(myName.truelength); //need to resolve in future
6 |
7 | let myHero = ["thor", "spiderman"];
8 |
9 | let heroPower = {
10 | thor: "hammer",
11 | spiderman: "sling",
12 |
13 | getSpiderPower: function () {
14 | console.log(`Spidy power is ${this.spiderman}`);
15 | }
16 | };
17 |
18 | Object.prototype.hitesh = function () {
19 | console.log(`Hitesh is present in all objects`);
20 | };
21 |
22 | // heroPower.hitesh();
23 | // myHero.hitesh();
24 |
25 | //let modify the power of array
26 | Array.prototype.heyHitesh = function () {
27 | console.log(`Hitesh says hello`);
28 | };
29 |
30 | // heroPower.heyHitesh();
31 | //myHero.heyHitesh(); //array can access the method
32 |
33 | //------------------------------ Inheritance:
34 | const user = {
35 | name: "chai",
36 | emai: "chai@google.com"
37 | };
38 | const Teacher = {
39 | makeVideo: true
40 | };
41 |
42 | const TeachingSupport = {
43 | isAvailable: false
44 | };
45 |
46 | const TASupport = {
47 | makeAssignment: "JS assignment",
48 | fullTime: true,
49 | ___proto__: TeachingSupport //Protypal Inheritance, it is out dated
50 | };
51 |
52 | //modern syntax of prototypal inheritance
53 | Object.setPrototypeOf(TeachingSupport, Teacher);
54 |
55 | //Scenario: need to calculate the true length of the string
56 | let anotherUsername = "ChaiAurCode ";
57 | String.prototype.truelength = function () {
58 | // console.log(`${this.anotherUsername.trim().length}`);
59 | console.log(`${this}`);
60 | console.log(`True length is: ${this.trim().length}`);
61 | };
62 | anotherUsername.truelength();
63 |
64 | "hitesh".truelength();
65 | "icetea".truelength();
66 |
--------------------------------------------------------------------------------
/src/05_iterations/06_filter.js:
--------------------------------------------------------------------------------
1 | /* //forEach example
2 | const coding = ["js","ruby","java", "python", "cpp"]
3 |
4 | const values = coding.forEach(item=>{
5 | // console.log(item);
6 | return item
7 | })
8 |
9 | console.log(values); */
10 |
11 | //filter
12 | /* const myNums = [1,2,3,4,5,6,7,8,9,10]
13 | //scenario: filter the values which are greater then 1
14 | const newNums = myNums.filter((num)=>(num > 4));
15 |
16 | console.log(newNums); */
17 |
18 | //alternate long way using forEach loop
19 | /* const myNums = [1,2,3,4,5,6,7,8,9,10];
20 |
21 | const newNum = []
22 | myNums.forEach((num)=>{
23 | if(num > 4){
24 | newNum.push(num)
25 | }
26 | });
27 | console.log(newNum); */
28 |
29 | //array of books given
30 | const books = [
31 | { title: "Book One", genre: "Fiction", publish: 1981, edition: 2004 },
32 | { title: "Book Two", genre: "Non-Fiction", publish: 1992, edition: 2008 },
33 | { title: "Book Three", genre: "History", publish: 1999, edition: 2007 },
34 | { title: "Book Four", genre: "Fiction", publish: 1989, edition: 2010 },
35 | { title: "Book Five", genre: "Science", publish: 2009, edition: 2014 },
36 | { title: "Book Six", genre: "Fiction", publish: 1987, edition: 2010 },
37 | { title: "Book Seven", genre: "History", publish: 1986, edition: 1996 },
38 | { title: "Book Eight", genre: "Science", publish: 2011, edition: 2016 },
39 | { title: "Book Nine", genre: "Non-Fiction", publish: 1981, edition: 1989 }
40 | ];
41 |
42 | //need to get the books whose genre is History
43 | const userBooks = books.filter((bk) => bk["genre"] === "History");
44 | // console.log(userBooks);
45 |
46 | //give the book, which are published after 2000
47 | const userBooksAfter1995AndGenreHistory = books.filter(
48 | (bk) => bk["publish"] >= 1995 && bk["genre"] === "History"
49 | );
50 | console.log(userBooksAfter1995AndGenreHistory);
51 |
--------------------------------------------------------------------------------
/src/09_advance_one/ApiRequest.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Document
7 |
8 |
9 |
10 | Value State Description
11 | 0 UNSENT Client has been created. open() not called yet.
12 | 1 OPENED open() has been called.
13 | 2 HEADERS_RECEIVED send() has been called, and headers and status are available.
14 | 3 LOADING Downloading; responseText holds partial data.
15 | 4 DONE The operation is complete.
16 |
26 |
27 |
80 |
81 |
--------------------------------------------------------------------------------
/src/09_advance_one/promises.js:
--------------------------------------------------------------------------------
1 | //creating the promise
2 | const promiseOne = new Promise(function (resolve, reject) {
3 | //do an async calls like DB Calls, cryptography calls, network related calls
4 | setTimeout(function () {
5 | console.log("Aysnc task is complete");
6 | resolve();
7 | }, 1000);
8 | });
9 |
10 | //consume the promise
11 | promiseOne.then(function () {
12 | console.log("promise consumed");
13 | });
14 |
15 | //------------------- 2nd way of creating the promise directly
16 | new Promise(function (resolve, reject) {
17 | setTimeout(function () {
18 | console.log("Async task 2");
19 | resolve();
20 | }, 1000);
21 | }).then(function () {
22 | console.log("async task 2 resolved");
23 | });
24 |
25 | //------------------ 3rd way of creating the promise: accessing the data
26 | const promiseThree = new Promise(function (resolve, reject) {
27 | setTimeout(function () {
28 | console.log("Aynsc task 3");
29 | resolve({ username: "chai", email: "chai@example.com" });
30 | }, 1000);
31 | });
32 |
33 | promiseThree.then(function (user) {
34 | console.log("Async task 3 is executed", user);
35 | });
36 |
37 | //-------------------- 4th way of creating the promise: lets see both resolve, reject
38 | //create the promise
39 | const promiseFour = new Promise(function (resolve, reject) {
40 | setTimeout(function () {
41 | console.log("Async task 4");
42 | let error = true;
43 | //if there is no error then resolve it
44 | if (!error) {
45 | resolve({ username: "hitesh", password: "123" });
46 | } else {
47 | reject("ERROR: Something went wrong");
48 | }
49 | }, 1000);
50 | });
51 |
52 | //consume the promise
53 | promiseFour
54 | .then((user) => {
55 | console.log("task 4 then");
56 | //lets see how to avoid callback hell
57 | console.log(user);
58 | return user.username;
59 | })
60 | .then((username) => {
61 | console.log("task 4 username");
62 | console.log(username);
63 | })
64 | .catch(function (error) {
65 | console.log(error);
66 | })
67 | .finally(function () {
68 | console.log("The promise is either resolve or reject");
69 | });
70 |
71 | //-------------------------- 5ht way to create the promise
72 | //create a promise
73 | const promiseFive = new Promise(function (resolve, reject) {
74 | setTimeout(function () {
75 | console.log("Async code 5");
76 | let error = false;
77 | if (!error) {
78 | console.log("resolved");
79 | resolve({ username: "javascript", password: "123" });
80 | } else {
81 | reject("ERROR: JS went wrong");
82 | }
83 | }, 1000);
84 | });
85 |
86 | //consume a promise
87 | async function consumePromiseFive() {
88 | try {
89 | //here i am just waiting, whether the result is resolved or rejected
90 | const response = await promiseFive;
91 | console.log("response:", response);
92 | } catch (error) {
93 | console.log(error);
94 | }
95 | }
96 |
97 | consumePromiseFive();
98 |
99 | //------------------------------- fetch using async await
100 |
101 | const url = "https://jsonplaceholder.typicode.com/users";
102 |
103 | async function getAllUsers() {
104 | try {
105 | const response = await fetch(url);
106 | console.log(response);
107 | const data = await response.json();
108 | console.log("response using fetch ", data);
109 | } catch (error) {
110 | console.log("Error:", error);
111 | }
112 | }
113 |
114 | getAllUsers();
115 |
116 | //------------------------- fetch using .then .catch: no need to write try-catch
117 | fetch(url)
118 | .then((response) => {
119 | return response.json();
120 | })
121 | .then((data) => {
122 | console.log(data);
123 | })
124 | .catch((error) => console.log(error));
125 |
--------------------------------------------------------------------------------
/src/07_projects/4-GuessNumber/chaiaurcode.js:
--------------------------------------------------------------------------------
1 | let randomNumber = parseInt(Math.random() * 100 + 1);
2 |
3 | const submit = document.querySelector("#subt");
4 | //get user input
5 | const userInput = document.querySelector("#guessField");
6 | const guessSlot = document.querySelector(".guesses");
7 | //show the last result
8 | const remaining = document.querySelector(".lastResult");
9 | const lowOrHi = document.querySelector(".lowOrHi");
10 | const startOver = document.querySelector(".resultParas");
11 |
12 | //to create the paragraph
13 | const p = document.querySelector("p");
14 |
15 | //store the value in array
16 | let prevGuess = [];
17 | let numGuess = 1;
18 | let playGame = true;
19 |
20 | //logic of the project
21 |
22 | //check, if it is available for game or not or user is allowed to play game or not
23 | if (playGame) {
24 | submit.addEventListener("click", function (e) {
25 | //prevent the value to send
26 | e.preventDefault();
27 | //select the user input
28 | const guess = parseInt(userInput.value);
29 | console.log(guess);
30 | //pass the function
31 | validateGuess(guess);
32 | });
33 | }
34 |
35 | //Create the function to validate between 1 to 100
36 | function validateGuess(guess) {
37 | if (isNaN(guess)) {
38 | alert("Please enter a valid number");
39 | } else if (guess < 1) {
40 | alert("Please enter a number more than 1");
41 | } else if (guess > 100) {
42 | alert("Please enter a number less than 100");
43 | } else {
44 | //push in array
45 | prevGuess.push(guess);
46 | //check is this last attempt
47 | if (numGuess === 11) {
48 | displayGuess(guess);
49 | displayMessage(`Game over Random number was ${randomNumber}`);
50 | endGame();
51 | } else {
52 | displayGuess(guess);
53 | //check whether the guess is correct or not, whether the number is higher or low
54 | checkGuess(guess);
55 | }
56 | }
57 | }
58 |
59 | //function to create the guess, if it is correct to validated number, tell that you won the game else reduce availibilty
60 | function checkGuess(guess) {
61 | if (guess === randomNumber) {
62 | displayMessage(`You guessed it right`);
63 | endGame();
64 | } else if (guess < randomNumber) {
65 | displayMessage(`Number is Too low`);
66 | } else if (guess > randomNumber) {
67 | displayMessage(`Number is Too high`);
68 | }
69 | }
70 |
71 | //display guess, clean the guess, update array
72 | function displayGuess(guess) {
73 | //update the userinput value with empty value or cleanup
74 | userInput.value = "";
75 | //add the values in guess slot
76 | guessSlot.innerHTML += `${guess} `;
77 | //increase the guess number
78 | numGuess++;
79 | //reduce the available guess
80 | remaining.innerHTML = `${11 - numGuess}`;
81 | }
82 |
83 | //display the message, based on user input value, if wrong reduce the number available. Print the user message
84 | function displayMessage(message) {
85 | //print the message here
86 | lowOrHi.innerHTML = `
${message}
`;
87 | }
88 |
89 | function endGame() {
90 | //first clear the input values
91 | userInput.value = "";
92 | //restrict the userinput, so that no new value to be added
93 | userInput.setAttribute("disabled", "");
94 | p.classList.add("button");
95 | p.innerHTML = `
Start new Game
`;
96 | startOver.appendChild(p);
97 | playGame = false;
98 | newGame();
99 | }
100 |
101 | function newGame() {
102 | const newGameButton = document.querySelector("#newGame");
103 | newGameButton.addEventListener("click", function (e) {
104 | // e.preventDefault();
105 | randomNumber = parseInt(Math.random() * 100 + 1);
106 | //reset the previous value
107 | prevGuess = [];
108 | numGuess = 1;
109 | guessSlot.innerHTML = "";
110 | remaining.inner = `${11 - numGuess}`;
111 | userInput.removeAttribute("disabled");
112 | startOver.removeChild(p);
113 | playGame = true;
114 | });
115 | }
116 |
--------------------------------------------------------------------------------
/src/02_Basics/04_objects.js:
--------------------------------------------------------------------------------
1 | // Object creation using constructor method
2 |
3 | // const tinderUser = new Object();
4 | const tinderUser = {};
5 | tinderUser["id"] = "123abc";
6 | tinderUser["name"] = "Siraj";
7 | tinderUser["isLoggedIn"] = false;
8 |
9 | // console.log(tinderUser);
10 |
11 | const regularUser = {
12 | email: "some@gmail.com",
13 | fullname: {
14 | userfullname: {
15 | firstname: "Hitesh",
16 | lastname: "Chaudhary"
17 | }
18 | }
19 | };
20 |
21 | console.log(regularUser["fullname"]?.["userfullname"]?.["firstname1"]);
22 | console.log(regularUser["fullname"]["userfullname"]["firstname"]);
23 |
24 | //Combining 2 objects
25 | const obj1 = { 1: "a", 2: "b" };
26 | const obj2 = { 3: "a", 4: "b" };
27 |
28 | // const obj3 = Object.assign({},obj1, obj2);
29 | const obj3 = { ...obj1, ...obj2 };
30 | // console.log(obj3);
31 |
32 | const users = [
33 | {
34 | id: 1,
35 | name: "sarfaraz"
36 | },
37 | {
38 | id: 2,
39 | name: "Hussain"
40 | },
41 | {
42 | id: 3,
43 | name: "Kamran"
44 | }
45 | ];
46 |
47 | // console.log(users[1]["name"]);
48 |
49 | // console.log(Object.keys(tinderUser));
50 | // console.log(Object.values(tinderUser));
51 | // console.log(Object.entries(tinderUser));
52 |
53 | // console.log(tinderUser.hasOwnProperty("isLoggedIn"));
54 |
55 | const course = {
56 | coursename: "js in hindi",
57 | price: 999,
58 | courseInstructor: "hitesh"
59 | };
60 |
61 | // course["courseInstructor"]
62 |
63 | // const { courseInstructor } = course;
64 | // console.log(courseInstructor);
65 | const { courseInstructor: instructor } = course;
66 | console.log(instructor);
67 |
68 | // {
69 | // "name": "hitesh",
70 | // "coursename" : "js in hindi",
71 | // "price" : "free"
72 | // }
73 |
74 | // {
75 | // "results": [
76 | // {
77 | // "gender": "male",
78 | // "name": {
79 | // "title": "Mr",
80 | // "first": "Jake",
81 | // "last": "Johnson"
82 | // },
83 | // "location": {
84 | // "street": {
85 | // "number": 9340,
86 | // "name": "Atkinson Avenue"
87 | // },
88 | // "city": "New Plymouth",
89 | // "state": "Hawke'S Bay",
90 | // "country": "New Zealand",
91 | // "postcode": 40098,
92 | // "coordinates": {
93 | // "latitude": "54.3480",
94 | // "longitude": "-70.9738"
95 | // },
96 | // "timezone": {
97 | // "offset": "+7:00",
98 | // "description": "Bangkok, Hanoi, Jakarta"
99 | // }
100 | // },
101 | // "email": "jake.johnson@example.com",
102 | // "login": {
103 | // "uuid": "85de0945-43a8-419d-a5b2-d55559691be6",
104 | // "username": "silvercat834",
105 | // "password": "egghead",
106 | // "salt": "qmNHhK2y",
107 | // "md5": "43651c2e4929e67f8f3cc62dc60a6027",
108 | // "sha1": "5f5a0dd8daeed9a6feec88b06fcd3a3b8b08aa67",
109 | // "sha256": "d0b34e0ff818d92035103f9f628444b43542d99a5f683fae547620c14e5e8810"
110 | // },
111 | // "dob": {
112 | // "date": "1963-11-27T17:49:29.823Z",
113 | // "age": 59
114 | // },
115 | // "registered": {
116 | // "date": "2009-07-27T23:16:53.106Z",
117 | // "age": 14
118 | // },
119 | // "phone": "(354)-517-9346",
120 | // "cell": "(765)-420-8407",
121 | // "id": {
122 | // "name": "",
123 | // "value": null
124 | // },
125 | // "picture": {
126 | // "large": "https://randomuser.me/api/portraits/men/36.jpg",
127 | // "medium": "https://randomuser.me/api/portraits/med/men/36.jpg",
128 | // "thumbnail": "https://randomuser.me/api/portraits/thumb/men/36.jpg"
129 | // },
130 | // "nat": "NZ"
131 | // }
132 | // ],
133 | // "info": {
134 | // "seed": "d9844274233862f9",
135 | // "results": 1,
136 | // "page": 1,
137 | // "version": "1.4"
138 | // }
139 | // }
140 |
--------------------------------------------------------------------------------
/src/07_projects/projectset1.md:
--------------------------------------------------------------------------------
1 | # Projects related to DOM
2 |
3 | ## Project link
4 |
5 | [Click here](https://stackblitz.com/edit/dom-project-chaiaurcode?file=index.html)
6 |
7 | # Solution Code
8 |
9 | ## Project 1
10 |
11 | ```javascript
12 | console.log("Sarfaraz");
13 | const buttons = document.querySelectorAll(".button");
14 | const body = document.querySelector("body");
15 |
16 | //As we got nodelist, so we can use forEach loop
17 | buttons.forEach(function (button) {
18 | console.log(button);
19 | //apply event listener on this button: means need to apply to listen
20 | button.addEventListener("click", function (e) {
21 | console.log(e);
22 | console.log(e.target);
23 | //check the id in target of the event
24 | if (e.target.id === "grey") {
25 | body.style.backgroundColor = e.target.id;
26 | }
27 | if (e.target.id === "white") {
28 | body.style.backgroundColor = e.target.id;
29 | }
30 | if (e.target.id === "blue") {
31 | body.style.backgroundColor = e.target.id;
32 | }
33 | if (e.target.id === "yellow") {
34 | body.style.backgroundColor = e.target.id;
35 | }
36 | });
37 | });
38 | ```
39 |
40 | ## Project 2
41 |
42 | ```javascript
43 | // we will get the form
44 | const form = document.querySelector("form");
45 |
46 | //form submition will be post, so we need to stop the submission
47 | //on submit click, get the values of height and weight
48 | form.addEventListener("submit", function (e) {
49 | //to stop the default submission
50 | e.preventDefault();
51 |
52 | //step to get the value of input
53 | //parseInt: convert the string value into int
54 | const height = parseInt(document.querySelector("#height").value);
55 | const weight = parseInt(document.querySelector("#weight").value);
56 | const results = document.querySelector("#results");
57 |
58 | //apply some checks, if those checks are correct than add the values
59 | //height should not be empty
60 | if (height === "" || height < 0 || isNaN(height)) {
61 | results.innerHTML = `Please give a valid height ${height}`;
62 | // height.innerHTML = '';
63 | // weight.innerHTML = '';
64 | } else if (weight === "" || weight < 0 || isNaN(weight)) {
65 | results.innerHTML = `Please give a valid weight ${weight}`;
66 | } else {
67 | //if everything is fine, then calculate the BMI
68 | const bmi = (weight / ((height * height) / 10000)).toFixed(2);
69 |
70 | //Show the results
71 |
72 | //check the result, whether it is under weight or over weight
73 | if (bmi < 18.6) {
74 | results.innerHTML = ` You have under weight of ${bmi}`;
75 | } else if (bmi > 18.6 && bmi < 24.6) {
76 | results.innerHTML = ` You have Normal Range of ${bmi}`;
77 | } else if (bmi > 24.6) {
78 | results.innerHTML = ` You have over weight of ${bmi}`;
79 | }
80 | }
81 | });
82 | ```
83 |
84 | ## Project 3
85 |
86 | ```javascript
87 | // We can use querySelector, but we are using getElementById
88 | // const clock = document.querySelector("#clock");
89 | const clock = document.getElementById("clock");
90 | console.log(clock);
91 |
92 | //we need to update the date and run it everytime
93 | //setInterval controls the interval, we set the time, it will run continuesly
94 |
95 | setInterval(function () {
96 | let date = new Date();
97 | // console.log(date.toLocaleTimeString());
98 | clock.innerHTML = date.toLocaleTimeString();
99 | }, 1000);
100 | ```
101 |
102 | ## Project 4
103 |
104 | ```javascript
105 | let randomNumber = parseInt(Math.random() * 100 + 1);
106 |
107 | const submit = document.querySelector("#subt");
108 | //get user input
109 | const userInput = document.querySelector("#guessField");
110 | const guessSlot = document.querySelector(".guesses");
111 | //show the last result
112 | const remaining = document.querySelector(".lastResult");
113 | const lowOrHi = document.querySelector(".lowOrHi");
114 | const startOver = document.querySelector(".resultParas");
115 |
116 | //to create the paragraph
117 | const p = document.querySelector("p");
118 |
119 | //store the value in array
120 | let prevGuess = [];
121 | let numGuess = 1;
122 | let playGame = true;
123 |
124 | //logic of the project
125 |
126 | //check, if it is available for game or not or user is allowed to play game or not
127 | if (playGame) {
128 | submit.addEventListener("click", function (e) {
129 | //prevent the value to send
130 | e.preventDefault();
131 | //select the user input
132 | const guess = parseInt(userInput.value);
133 | console.log(guess);
134 | //pass the function
135 | validateGuess(guess);
136 | });
137 | }
138 |
139 | //Create the function to validate between 1 to 100
140 | function validateGuess(guess) {
141 | if (isNaN(guess)) {
142 | alert("Please enter a valid number");
143 | } else if (guess < 1) {
144 | alert("Please enter a number more than 1");
145 | } else if (guess > 100) {
146 | alert("Please enter a number less than 100");
147 | } else {
148 | //push in array
149 | prevGuess.push(guess);
150 | //check is this last attempt
151 | if (numGuess === 11) {
152 | displayGuess(guess);
153 | displayMessage(`Game over Random number was ${randomNumber}`);
154 | endGame();
155 | } else {
156 | displayGuess(guess);
157 | //check whether the guess is correct or not, whether the number is higher or low
158 | checkGuess(guess);
159 | }
160 | }
161 | }
162 |
163 | //function to create the guess, if it is correct to validated number, tell that you won the game else reduce availibilty
164 | function checkGuess(guess) {
165 | if (guess === randomNumber) {
166 | displayMessage(`You guessed it right`);
167 | endGame();
168 | } else if (guess < randomNumber) {
169 | displayMessage(`Number is Too low`);
170 | } else if (guess > randomNumber) {
171 | displayMessage(`Number is Too high`);
172 | }
173 | }
174 |
175 | //display guess, clean the guess, update array
176 | function displayGuess(guess) {
177 | //update the userinput value with empty value or cleanup
178 | userInput.value = "";
179 | //add the values in guess slot
180 | guessSlot.innerHTML += `${guess} `;
181 | //increase the guess number
182 | numGuess++;
183 | //reduce the available guess
184 | remaining.innerHTML = `${11 - numGuess}`;
185 | }
186 |
187 | //display the message, based on user input value, if wrong reduce the number available. Print the user message
188 | function displayMessage(message) {
189 | //print the message here
190 | lowOrHi.innerHTML = `
${message}
`;
191 | }
192 |
193 | function endGame() {
194 | //first clear the input values
195 | userInput.value = "";
196 | //restrict the userinput, so that no new value to be added
197 | userInput.setAttribute("disabled", "");
198 | p.classList.add("button");
199 | p.innerHTML = `
Start new Game
`;
200 | startOver.appendChild(p);
201 | playGame = false;
202 | newGame();
203 | }
204 |
205 | function newGame() {
206 | const newGameButton = document.querySelector("#newGame");
207 | newGameButton.addEventListener("click", function (e) {
208 | // e.preventDefault();
209 | randomNumber = parseInt(Math.random() * 100 + 1);
210 | //reset the previous value
211 | prevGuess = [];
212 | numGuess = 1;
213 | guessSlot.innerHTML = "";
214 | remaining.inner = `${11 - numGuess}`;
215 | userInput.removeAttribute("disabled");
216 | startOver.removeChild(p);
217 | playGame = true;
218 | });
219 | }
220 | ```
221 |
222 | ## Project 6
223 |
224 | ```javascript
225 | //Generate random color
226 |
227 | const randomColor = function () {
228 | const hexValue = "0123456789ABCDEF";
229 | let color = "#";
230 |
231 | for (let i = 0; i < 6; i++) {
232 | color += hexValue[Math.floor(Math.random() * 16)];
233 | }
234 | return color;
235 | };
236 |
237 | //we will get the generated value, we need 16 value, so we will get value from 0 to 16
238 | // console.log(Math.floor(Math.random() * 16));
239 |
240 | // console.log(randomColor());
241 | let intervalId;
242 | const startChangingColor = function () {
243 | if (!intervalId) {
244 | intervalId = setInterval(changeBGColor, 1000);
245 | }
246 | function changeBGColor() {
247 | document.body.style.backgroundColor = randomColor();
248 | }
249 | };
250 | document.querySelector("#start").addEventListener("click", startChangingColor);
251 | const stopChangingColor = function () {
252 | clearInterval(intervalId);
253 | intervalId = null;
254 | };
255 | document.querySelector("#stop").addEventListener("click", stopChangingColor);
256 | ```
257 |
258 | ## Project 5
259 |
260 | ```javascript
261 | const insert = document.querySelector("#insert");
262 |
263 | //add event listenenr on whole window
264 | window.addEventListener("keydown", function (e) {
265 | insert.innerHTML = `
266 |
7 |
8 |
9 |
10 | ## Lecture 1:
11 |
12 | - Getting confidence in software development is very important
13 | - Doing project will only gives you the confidence
14 | - Confidence will only clear up the interviews
15 | - No extra tool required to setup to learn javascript
16 |
17 |
18 |
19 |
20 | ## Lecture 2: Setting up local environment
21 |
22 | - Javascript execution is same for browser or running on any environment
23 | - Every source code has meaning in javascript, like console.log() has some meaning in javascript, it is syntax in programming language
24 | - Every programming language comes with some extenstion like .js, .py
25 | - Every software has capability to understand the syntax whether it is .js or .py, which we call interpretor or compiler
26 | - The compiler / interpretor was hidden in browser but now taken out in nodejs enviroment
27 | - Now we no need to write, index.html and create the seaprate js file and add in script, as it was attached with broweser.
28 | - Now we can run javascript directly with node environment, Hence Javascript is used everywhere like in frontend, backend etc
29 | - Install the nodejs from nodejs.org and run in the local machine
30 | - For writing the code use, VS Code, as it very popular now a days, it is from microsoft
31 | - VS Code will help in color correction, indentation etc
32 | - Go to view ➜ terminal, here you can see the terminal
33 | - Check whether node is installed or not: node -v, our work done, if we get some number like 18, then we are ok
34 | - To execute the code, we use: node filename
35 |
36 |
37 |
38 |
39 | ## Lecture 3: Github
40 |
41 | - We have lot of online code execution environment available like Github.
42 | - Lets see, how can we setup the code environment in Github,
43 |
44 | - Go to Github and create the account
45 | - Create new repository ➜ code-with-javascript-one
46 | - Create the **README.md** and create the repository
47 | - There are different to use Github, but here we will see codespace
48 | - click on code ➜ codespaces
49 | - We will get the vscode here, here wee will get the computer like environment
50 | - Here click file ➜ view ➜ command palletter ➜ write 'Container' ➜ Add Dev container Configuration Files
51 | - It means, we are adding the configuration files
52 | - Click Show all configuration ➜ node.js & Javascript ➜ click default ➜ ok ➜ rebuild ➜ it will add some execution files
53 | - How to push the code to the github:
54 | - 1. click on source control ➜ add the file on + click ➜ add message ➜ click on commit
55 | - 2. click on triple dot ➜ click on push
56 | - Reload the github to get the files updated
57 | - To stop the github codespaces
58 | - Click on codespace ➜ see owned by 'username' on right side ➜ click on 3 dot ➜ delete the working directory ➜ ok
59 | - We can start the machine when needed
60 |
61 |
62 |
63 |
64 |
65 | ## Lecture 4: Variables & Constants
66 |
67 | 
68 |
69 | - Only people will survive in the Tech indutry whos motive is to create something product
70 | - Through javascript, we can create, mobile app, web app etc
71 | - Set goal to create Ecommerce app or social media app
72 | - All game is about mindset, here mideset to create a sample product
73 | - Think to create a ecomerce app
74 | - I need to attract user and make him into register
75 | - Given him/her unique id
76 | - When user comes ➜ he enter the details like name, city, etc, it needs to store ➜ it ll stored in memory space, here it is varaible later DB ha
77 | - Here, all the game is about, storing the data and retriving it
78 | - So we learn variable and constants
79 | - variable can be change but constant is constant
80 | - We will learn about investigation
81 | - We should the name that is easily readable
82 | - When we see the var, let, const, it means, we need to assign in memory
83 | - Const means, we cant change the value, it will through an error, if we try to change the constant value
84 | - To write a comment, we use // 2 slashes, it means, javascript cant execute this lines
85 | - We can print multiple values in console.log([]) like this by separting commas
86 | - In js, let and const and be done using let and const
87 | - In js, there was a problem of scope, means anything written in {}
88 | - In js, when some programmer change the value in scope, it will impact the existing varaible
89 | - So in modern js, we use let, const to overcome the issue of block scope and function scope
90 | - /* */ this is also way of comment
91 | - We can reserve the variable without using anykeyword as well, but it is not good practice
92 | - In js, semicolon is optional
93 | - Defualt value of let is undefined
94 |
95 |
96 |
97 |
98 |
99 | ## Lecture 5: Datatypes
100 |
101 | - Prefer to practice on keyboard rather then taking notes on paper, write notes here itself so to remember
102 | - **"use strict"** if we use above 2 words, it means it is newer version of javascript
103 | - alert("hello") if we run the code, it ll given an error saying node is not defined, as js engine is hidden in browser ➜ it means, to run alert() has different way ti run it.
104 | - In coding readability is very important ans it should be future proof
105 | For documentation prfer mdn (mozilla documentation)
106 | - Original documenataion would be find in tc39.es
107 | - ECMA Script is the standard way of writing javscript
108 | - **For Example:** if we write loop, then we should write in this way etc
109 | - In js , we have different datatype,
110 | - Primitive Datatype:
111 | - Like number, string, boolean, null, undefined, bigInt, symbol
112 | - Prefer to use double quotes for string datatype
113 | - Boolean will say yes or no, it has only 2 values
114 | - null ➜ it is standalone value, yes it is datatype as well
115 | - null is representaiton of empty value
116 | - null means value is empty, example, like giving empty value while monitoring the temp, as we cant give 0, as 0 has some value in temp scale
117 | - ndefined ➜ means some value is not defined
118 | - Symbol datatype is used to fincdout the uniquness ➜ it is used in react, to find the component
119 | - typeof ➜ to know the type of any variable, we use typeof
120 | - **Example:**
121 | ```javascript
122 | console.log(typeof "sarfaraz") ➜ string
123 |
124 |
125 |
126 |
127 | ## Lecture 6: Conversion Operation
128 |
129 | 
130 |
131 | - We dont in javascript, what type of value we get, so we need to use conversion of datatype
132 | - We can write typeof in 2 ways
133 | - typeof variablename
134 | - typeof(variableName)
135 | - To convert string into Number, we use Number(variableName);
136 | - When value is not proper number like 33abc, its type is NaN
137 | - In Javascript, there is no strict check, so we use typescript
138 | - Conversion of null into number is 0
139 | - Conversion of undefined into number is NaN
140 | - Conversion of boolean into number is false
141 | - Conversion of string into number is NaN, as it is not able to convert into number
142 | - **Number conversion summary:**
143 | ```javascript
144 | "33" => 33
145 | "33abc" => NaN
146 | true => 1; false =>0
147 | - It is very important to know, is the value is converted and know what value it gives us back.
148 | - Conversion of 1 gives true
149 | - Conversion of "" emty string gives false;
150 | - **Boolean conversion summary:**
151 | ```javascript
152 | 1 => true, 0=> false
153 | "" => false
154 | "Sarfaraz" => true
155 |
156 |
157 |
158 |
159 |
160 | ## Lecture 7: Operations
161 |
162 | - if string is 1st then all conversion will into string
163 | - **Example:** ```javascript console.log("1"+2+2) ➜ 122```
164 | - If the string is last then conversion will be done before that then string will be added
165 | - **Example:**
166 | ```javascript
167 | console.log(1+2+"2") ➜ 32
168 | - Should know about more about convertion: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment
169 |
170 |
171 |
172 |
173 |
174 | ## Lecture 8: Comparisons
175 |
176 | - Comparison shouild be done with same datatype only
177 | - Here console.log("2" >1) will be converted into 2>1 condition, here the auto conversion happens
178 | - While comparion null is converted into 0 or NaN, example console.log(null > 0), means 0 > 0, hence answer is false. So avoid only value check but use value with datatype check.
179 | - Comparison with undefined with 0 is always false, example: console.log(undefined == 0); it gives false
180 | - In Javascript, comparison and equality check both work differently
181 | - **==== Strict check:** it will check value as well as data type
182 |
183 |
184 |
185 |
186 |
187 | ## Lecture 9: Datatype summary
188 |
189 | - Datatype is basically into 2 types
190 | - Primitive
191 | - Non-primitive
192 | - Difference between is call by value and call by reference, it means how we are saving the data into memory and how we are accessing the data
193 | - **Primitive Datatype:**
194 | - Primitive is into 7 categories
195 | - Prmitive datatype is call by value
196 | - when we take the data, it is copied, so the changes are done on copied data
197 | - String, Number, Boolean, null (meam empty), undefined, Symbol (to make the value unique), BigInt
198 | - **Non-Primitive Datatype:**
199 | - It is also called as reference type
200 | - we can get the reference of the available data
201 | - Array, Objects, Functions
202 |
203 | - **To master the javascript:** Learn Objects and browser events
204 |
205 | - JavaScript is a dynamically typed language, which means that data types of variables are determined by the value they hold at runtime and can change throughout the program as we assign different values to them
206 | - For big integer number, we add n at the end of the number.
207 | - Object is declared with curly brases
208 | - Datatype of function is called object function
209 | - **Reference Documentation link:** https://262.ecma-international.org/5.1/#sec-11.4.3
210 |
211 |
212 |
213 |
214 |
215 | ## Lecture 10: Stack and Heap Memory
216 |
217 | 
218 |
219 | 
220 |
221 | - Memory is of 2 types 1. Stack 2. Heap Memory
222 | - Stack memory is used for primitiva datatype while heap memory is used for non primitive datatype
223 | - To draw online diagram use: https://excalidraw.com/
224 | - we will get original value reference when take back the value from reference value
225 | - Whatever goes in heap, we only get the reference, means whatever changes we are doing, we are doing in original value
226 | - From stack, we get the copy of the value
227 |
228 |
229 |
230 |
231 |
232 | ## Lecture 11: String in javascript
233 |
234 | - Through string, we can use modern syntax to write it.
235 | - We denote string single or double quote '' / ""
236 | - In modern days, we need to use backticks `` for strin manipulation called string interpolation.
237 | - All methods are available in **__proto__** for string, example toUpperCase() etc
238 | - If we use methods related to **__proto__** then original value is not changed.
239 | - we can check what character available we use charAt(index)
240 | - **indexOf('charactor') :** we can get the index of the charactor
241 | - **substring(0,4)** the last value is excluded.
242 | - **trim() :** this method is used to remove the unwanted space, mostly it is used in filling the form
243 | - **split('-') :** split mothod is used to split with specified digit and gives the output in arrays
244 |
245 |
246 |
247 |
248 |
249 | ## Lecture 12: Numbers and Maths
250 |
251 | - If we write const score=400, then Javscript will recognise it as number, but we can explicitly define numbers as new Number(400)
252 | - we can convert number into string using toString() method, it will help me to use string methods
253 | - **toFixed() :** to give the precision value till few decimal values, like toFixed(2) ➜ it wwill give .00 like that
254 | - **toPrecision(3):** it will focus on only 3 digit value only
255 | - **toLocaleString('en-IN') :** this method will be helpful in giving the output in redable format of number, like 1000000 ➜ 1,000,00
256 | - **Maths.abs():** it will convert -ve value into +ve value, +ve will remain +ve, it helps to convert valeue into +ve value.
257 | - **Math.round():** To get the round value, example: Math.round(4.3) ➜ 4
258 | - **Math.ceil():** It will round the value to top. Example: Math.ceil(4.6) ➜ 5 or Math.ceil(4.2) ➜ 5
259 | - **Math.floor():** It will take bottom value, Example: Math.floor(4.2) -6-> 4.2 or Math.floor(4.6) ➜ 4, It will always takes the lowest value
260 | - Mostly we will use round() method instead of ceil and floor
261 | - **Math.min():** we can findout the minimum value from the given numbers, example: Math.min(3,4,5,6,) ➜ 3
262 | - **Math.max():** we can findout the maximum value from the given numbers, example: Math.min(3,4,5,6,) ➜ 6
263 | - **random():** it will the random value between 0 and 1
264 | - To make the value in 1 digit then add 1, example: (Math.random()*10)+1
265 | - We can round of the value using Math.floor in random method
266 | - We can add 10, if we want the value more then 10
267 |
268 |
269 |
270 |
271 |
272 | ## Lecture 13: Date and Time
273 |
274 | - **Reference:** https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
275 | - Date is calculted in milli second starting from January 1st
276 | - In future, we will be using Temporal object like Math, which will contain all the methods, but as of we will be using Date object only.
277 | - Date can be converted into string using toString() method
278 | - **toLocaleDateString():** It will give the value with date with / format Example: 9/27/2023
279 | - **toLocaleString():** It will give the date value with time with / format Example: 9/27/2023, 7:05:46 PM
280 | - In short: Every date method will add or remove some format
281 | - Data type of Date is object
282 | - Note: Month will start from 0 in javascript, but when we give the date in format it starts with 1, Example new Date("2023-01-23") ➜ 1/23/2023
283 | - timestamp will be used, when we want to give the polls, like who has given the fastest answer
284 | - **Date.now():** It will give the current date in milli second
285 | - We can get the details about date using other method starting with get,
286 | - **Example:**
287 | ```javascript
288 | let newDate = new Date();
289 | console.log(newDate.getMonth()+1) ➜ 9, added 1 as date always starts with 0.
290 | - We can customise the date format,
291 |
292 | **Example:**
293 | ```javascript
294 | newDate.toLocaleString('default',{ weekday: "short"}) ➜ Wed, as today is Wednesday
295 |
296 |
297 |
298 |
299 |
300 | ## Lecture 14: Array
301 |
302 | 
303 |
304 | - Array has squre brakcet, Array has elements in it.
305 | - **Reference Documentation:** https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
306 | - We can store the muliple values in single variable
307 | - Javascript array are resizable
308 | - Array indexing starts with 0
309 | - we can access the array using indexing, Example: myArr[0]
310 | - When we copy array, the array creats shallow copy, means share same reference point, means, it will change the original array, while Deep copy do not share the same reference
311 | - We can declare the array using 2 types
312 | - Using square brakcet []
313 | - Using **new Array()**. here it will add the square bracket by its own
314 | - We can view all the methods available in array.
315 | - **Example:**
316 | ```javascript
317 | const numbers = [1,2,3,4];
318 | console.log(numbers) ➜ click on prototype to see the methods
319 | - Array contain the mixed data type
320 | - Array ha prototype proerty access
321 | - Array has length property , to calculate the length of an array
322 | - **push():** It will add the value in the array
323 | - **pop():** Remove the last available value in array
324 | - **unshift():** Value will be added at the start, But here problem is, we need to shift all values to right
325 | - **shift():** remove the first element from an array
326 | - Some array method will answer in yes or no, like includes(), so based on true or false, we can write the condition and judge the value
327 | - **join():** add all the element in the array but gives output into string
328 | - **slice():** It will not update the orignal array, here last range is not included, will give the extracted array from start to end value
329 | - **splice():** It will update the original array, Gives the extracted array as output.
330 | - **concat():** It will combine 2 arrays and gives the new array
331 | - **spread operator:** think glass of water, when glass fall ➜ water spread to the ground : remember
332 | - In spread operator, we will get the spread out values
333 | - **flat():** This method is used to flatten the array, we need to mention the depth as a pramater
334 | - **Array.isArray():** To check the given array is array or not, it will give true or false response
335 | - **Array.from():** this method will convert any given number/name into array
336 | - If we pass an array in from, then we need to mention, do we need to create the array for keys or values
337 | - **Array.of() :** Will give the newly formed array, will convert any values into new array
338 |
339 |
340 |
341 |
342 |
343 | ## Lecture 15: Objects
344 |
345 | 
346 |
347 | - To master javascript, we need to learn 2 things
348 | - Objects
349 | - Events
350 | - Objects can be declared in 2 ways
351 | - Literal
352 | - Constructor
353 | - **Singleton:** It means, only 1 object is created.
354 | - When the object is created using constructor, it is singleton
355 | - **Example:** const JsUser = {}
356 | - Object has keys and values
357 | - By Default key is in the string format in object
358 | - To access the object element, we use JsUser["name"] , it means we are accessing using string
359 | - we can update the value of the user using = equal to
360 | - We can freeze the object using Object.freeze() to avoid the further update
361 | - To define Symbol, we use square bracket [], it says I am a symbol
362 | - Function can be treated as a varaible in javascript
363 | - We can get the reference if we dont give paranthesis in function call with object, example: JsUser.greeting ➜ [Function (anonymous)]
364 | - If we want to reference the same object, then we can use 'this'
365 |
366 |
367 |
368 |
369 |
370 | ## Lecture 16: Objects 2: Object using constructor
371 |
372 | - We can create the object using {} or new Object(), here both are same
373 | - We can have any level of nesting in object
374 | - we can access the object key using [], for nested value we can use [][], Example : regularUser["fullname"]["userfullname"]["firstname"]
375 | - We can use optional chainging to avoid the error: ?.
376 | - **Object.assign():** This method copies all the values of an objects
377 | - We can extract keys using Object.keys and values using Object.values from an object
378 | - **Object.entries() :** To get all the values of object in key value pair
379 | - **hasOwnProperty():** To check the property exists in object or not
380 | - To check the different mehoda available in object, use this trick
381 | - Go to browser console
382 | - ```javascript
383 | const obj1 = {1:"a",2:"b"} ➜ obj1 ➜ chec all the methods in [prototype]
384 |
385 |
386 |
387 |
388 |
389 | ## Lecture 17: Objects Destrcuturing and JSON API
390 |
391 | - Object destructuring is a syntactically sugar, means it only provide the syntax
392 | - Object destructuring helps in avaoiding the repeatability of the code
393 | - In Object destructuring, we are extracting the property from object
394 | - We can rename the destructure value using colon :
395 | - When we go to the restaurant and order something, the menu card is API Documentation
396 | - When we order 'Samosa', we should not worry how it is made, just we have cOnsume it, Somosa is created at the backend, same goes with API.
397 | - JSON is almost written like object, but key, value pair are stored in string
398 | ```json
399 | {
400 | "name": "hitesh",
401 | "coursename" : "js in hindi"
402 | }
403 | ```
404 | - Use the url : https://api.github.com/users/hiteshchoudhary
405 | - Use the API ➜ As the value is into JSON ➜ convert in javascript object ➜ use it, enjoy
406 | - **Famous API:** Random user me: https://randomuser.me/ ➜ use https://randomuser.me/api/
407 | - We can beautify the JSON using JSON Formatter online editor: https://jsonformatter.org/ ➜ we can beautify the JSON and check it into tree structure ➜ after this we can see how can we deal with it, may be using array or object
408 |
409 |
410 |
411 |
412 | ## Lecture 18: Functions and parameters
413 |
414 | 
415 |
416 | - While learning about functions, it is important to know about memory management as well.
417 | - Function means, what the 10, 20 etc lines of code you have writte, we kept in package
418 | - We can resue the package, as much as we want
419 | - To write a function, we give function keywoes, function name, then pranthesis then scope of function, this is called function defination
420 | - To call the function, we function name with parenthesis, then function will execute it.
421 | - In javascript, it automatically check the datatype of value, so it is important to check the type of any variable before doing any operations
422 | - **function parameter :** while creating the function defination, whatever the inputs we take, we call it as parameters
423 | - **function arguments:** The values which we pass in the function call, we call it as an argument
424 | - It is important to know, what we are sending form the function
425 | - **Note:** Whatever you write after function return, nothing will work
426 | - undefined and "" empty string is considered as false value
427 | - So to check the error, check with false value ➜ Example: if(!username)
428 | - We can give default value in function parameter with equals to, Example loginUserMessage(username = "sam") ➜ it will avoid to go into error check, if no username available
429 | - **Rest Operator:** ... when these 3 dots comes in parameter, it means get all the values and give me in bundle.
430 | - **Example:** Get all the values in cart value
431 |
432 |
433 |
434 |
435 | ## Lecture 19: Global and local scope
436 |
437 | - Scopes story starts with var, let and const
438 | - **{} :** This is called as scope
439 | - When {} comes with function or if, then we called its scope
440 | - When any thing declared inside {} it is called block scope, and outside of {} is called global scope
441 | - value declare in global scope ➜ it is available in block scope but value declaredin block scope is not available in global scope.
442 | - var is functional scope, where as const, let are block scope.
443 | - Global scope is different for node environment and browser
444 |
445 |
446 |
447 |
448 | ## Lecture 20: Scope level and mini hoisting
449 |
450 | - {} Is only scope in javascript ha
451 | - Kids can ask ice cream from elder but it is awekword if elder ask the ice cream from kids
452 | - It means, inner function can access the variable from outside but outside function cant ask inner member variables etc
453 | - Variable declared inside the insode function cant be access outside function
454 | - Every time function is called, then every time it is kept in stack
455 | - Closure in simple line, the inner function can access the outside declared variable
456 | - There are 2 technique to create a function, using bassic function, other is function expression
457 | - Hositing is not possible with function expression, but hoisting is possible with basic function only
458 |
459 |
460 |
461 |
462 | ## Lecture 21: this and arrow function
463 |
464 | - ES6 came in 2015 and came with lots of new features
465 | - Arrow function and this keyword are the features of ES6
466 | - this keyword tells about current context
467 | - When we refer to the current context of the object, we use this keyword
468 | - In node environment, current object refer to empty object
469 | - Node javascript engine is stand alone, earlier javascript engine is in a browser
470 | - In brower there is a global object called window object
471 | - this keyword is not accessible in noraml function and function expression (doubt)
472 | - To write arrow function, replace function keyword with qual and arrow in function expression
473 | - **Note:** this keyword can be accessible in normal function, act as a global object but not in arrow function
474 | - **syntax of arrow function:** const sampleArrowFunction = ()=> {}
475 | - **Implicit Return:** when arrow function is 1 liner, then we consider it as implicit return and no need to write the return keyword
476 | - if use curly braces, ➜ then need to use return. If we use paranthesis, then no need to add the return keyword.
477 | - To return the object, we should wrap in parenthesis
478 |
479 |
480 |
481 |
482 | ## Lecture 22: Immedietly Invoked function
483 |
484 | - The function which has its own scope and executed immideitly
485 | - **IIFE:** Function defination is wrapped in paranthesis and use empty parenthesis for execution: ()()
486 | - Note: To avoid the use of global variable, as global variable pollute the variable, so we use IIFE
487 | - Note: To stop the IIFE, It is important to add the semicolon after IIFE
488 | - We can write IIFE using normal function as well as arrow function
489 | - Remember 2 IIFE can be written by seperating semicolon
490 |
491 |
492 |
493 |
494 | ## Lecture 23: Javascript Behind scene
495 |
496 | - Remember how the call stack works in javascript
497 | - Javascript Execution context: it means, the javascript created by you, how it will run
498 | - Javascript has 2 execution context:
499 | 1. Global execution context: It is store in 'this', executed in thread, remember javascript is single threaded language
500 | 2. Functional execution context
501 | - Javascript runs the code into 2 phases
502 | 1. Memory creation phase:
503 | - Memory is created for variables and functions declared, it is not executed here
504 | - Just variables are created, and kept with us
505 | 2. Execution Phase: we will get all the values
506 | - lets see with the example:
507 |
508 | ```javascript
509 | let val1 = 10;
510 | let val2 = 5;
511 | function addNum(num1, num2){
512 | let total = num1 + num2;
513 | return total;
514 | }
515 | let result1 = addNum(val1, val2)
516 | let result2 = addNum(10, 2)
517 | ```
518 | 1. Memory Creation Phase: Here, In 1st cyle we will get
519 | - val1 -> undefined
520 | - val2 -> undefined
521 | - addNum -> defination
522 | - result1 -> undefined
523 | - result2 -> undefined
524 | 2. Execution Phase:
525 | - val1 <- 10
526 | - val1 <- 5
527 |
528 | - For addNum function, now different execution phase will be created
529 | - 1. New variable environment
530 | - 2. Execution thread
531 | - Memory phase:
532 | - val1 -> undefined
533 | - val2 -> undefined
534 | - total -> undefined
535 | - Execution context: Here execution happens
536 | - num1 -> 10
537 | - num2 -> 5
538 | - total -> 15 ➜ total will return to global execution context
539 | - The execution context will be deleted after the work is done
540 | - result1 -> 15
541 | - result2 -> here again 2 phased will be created
542 | 1. Memory phase
543 | 2. Execution Phase
544 | - here again the total will be calculated and sent to the execution context
545 | - **Callstack:** All the method will be executed here, it will be removed once the work is done
546 | - It follow the LIFO
547 | - We can check the flow of function call by giving break points
548 |
549 |
550 |
551 |
552 | ## Lecture 24: Control flow
553 |
554 | - In if statement, if the condition is true then only code will execude for if statement
555 | - If statment will be having comparison statement
556 | - Following are the comparator operators checking:
557 | - Less then < ➜ Example: 10 < 20 ➜ check 10 is less then 20, yes it is, so output: true
558 | - Greated then >
559 | - Less then and equal to <=
560 | - greater then and equal to >=
561 | - Equal to ==, note single operator is assignmnet operator, Example: const isLoggedIn = true, means true is assigned to isLoggedIn, but here == is comparison operator
562 | - Not Eqaul != ➜ 3 !=2 ➜ -ve checking ➜ 3 is not equal to 2 ➜ output: true
563 | - === will check the type and value, it is strict equality check
564 | - !== It will do -ve type and value checking
565 | - else is conditional code, it will executed either if statement or else statement
566 | - Scope is counted in curly braces {}
567 | - var scope is compltely global, it means, it accessable outside {} as well
568 | - **&& :** and condition will check both left and right condition
569 | - **Example:** Do you need to buy phone and cover ➜ yes
570 | - If any of the condition is wrong in &&, the block will not get executed
571 | - **|| :** called pipe sign, help to multiple check or condition
572 |
573 | #### Switch case:
574 |
575 | - Using switch case, we will be checking multiple values
576 | **syntax:**
577 | ```javascript
578 | switch(key){
579 | case value:
580 | break;
581 | default:
582 | break;
583 | }
584 | ```
585 | - Here key is the condition, we need to check everytime
586 | - Use intellesence or seuggestion in vscode for switch case
587 | - If nothing match, then default case will be excuted
588 | - whenever, key is match rest all code will be executed, so we give break to avoid limited details to show
589 |
590 | #### Truthy & flasy values
591 |
592 | - Any value added in string is truthy value
593 | - [] empty arry, empty object are truthy value
594 | - If only function is declared, then that is also truthy value
595 | - Object.key() will return the array
596 | - **Remember:** it is true comparison below
597 | - false == 0 ➜ true
598 | - false == '' ➜ true
599 | - 0 == '' ➜ true
600 | - && || are called logical operator
601 |
602 | #### Nullish Coalescing Operator (??)
603 |
604 | - Need to focus on Null and undefined values
605 | - ?? it will check the safty value, based on null or undefined it will assign some other value
606 | - While using ?? operator twice, it will take the 1st assigned value, Example: null ?? 10 ?? 10 ➜ output: 10
607 | - ?? is basically used to handle errors
608 | - nullish and null operator are 2 different thing
609 | - Ternary operator: it is short cut of writing if else statement
610 | - Syntax: condition ? true : false
611 |
612 |
613 |
614 |
615 | ## Lecture 25: for loop, break and continue
616 |
617 | 
618 |
619 | - use ctrl + d : to select the multiple value at once
620 | - To stop any control, we use break keyword
621 | - continue is like, sorry for 1 time (means skip when the condition match) and continue the process remain
622 |
623 |
624 |
625 |
626 | ## Lecture 26: while, do while loop
627 |
628 | - There are many loops, there are different ways to solve the problem.
629 | - Logically, we need to do the same, what we did in for loop, like initialisation, checking condition, increment or decrement
630 | ```javascript
631 | // While syntax
632 | while(condition){
633 | // if above condition is match, then execute the statment
634 | }
635 | ```
636 | - Readability of the code is very important
637 | ```javascript
638 | //do while syntax
639 | do{
640 | //statement
641 | //increment / decrement
642 | }while(condition)
643 | ```
644 | - In do-while, work is done first then later condition is checked
645 | - Mostly we dont use d0-while loop, as we check the condition first
646 | - It is very very common to loop the array, as the API Value, DB values comes in the form of array
647 |
648 |
649 |
650 |
651 | ## Lecture 27: Higher order array loops
652 |
653 | - There are other loops in array like for-in, for-of, forEach, its our choice what to use.
654 | - There is very common scenario, where we can have
655 | - strings in array ["","",""]
656 | - Objects in array [{},{},{}]
657 | - So we need to iterate it, so use higher order array loops
658 | - string, array, objects are iterators, so we can use loops on it.
659 | - **Syntax of for...of loop:**
660 |
661 | ```javascript
662 | for(const iterator of object){
663 |
664 | }
665 | ```
666 | - Above object is used as a broader term, it means, on what you want to use loop, dont confused with javascript object
667 | - In for...of loop, there is no need to worry about initialisation, increment or decrement.
668 | - Instead of giving names like i,j, it is better to use meaningful name, like greetings, greet, numbers, num etc
669 | - Map is use to store key, value pair
670 | - **Reference:** https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
671 | - Map is like object with slight difference
672 | - Map is used to store unique values, persist the same order how it entered
673 | - We can iterate the Map using for...of loop by destructuring the value
674 | ```javascript
675 | for(const [key, value] of countries){
676 | console.log(`Key: ${key} Value: ${value}`)
677 | }
678 | ```
679 | - Note: Not possible to iterate the object using for..of
680 |
681 | #### Object iteration:
682 |
683 | #### for...in loops
684 | - **for...in loop syntax:**
685 | ```javascript
686 | for(const key in myObject){
687 |
688 | ```
689 | - To retrive value from object, we use objectName[key]
690 | - Maps are not iterable so we cant use for..in loop for Map
691 |
692 | #### forEach loop
693 | - For most of the time, we may use forEach loop for array
694 | - Array has some inbuilt methods, here forEach method, so we can use it to access the elements of an array
695 | - Passing callback means give me the function to operate
696 | - callback function doesn't have name
697 | - While iterating an array, every time the function will get executed, and take as a pramater to it.
698 | - forEach doesnt only return item, but it will return item, index and whole array
699 | - callback has access to all the element of an array
700 |
701 |
702 |
703 |
704 | ## Lecture 28: filter, map and reduce
705 |
706 | #### filter():
707 | - forEach dont return any value, either you wanted or not
708 | - filter return some values
709 | - filter is having callback function which has access to each element, then we have to give the condition. If the condition is satisfies then return those values else dont return the values
710 | - When we write paranthesis, then no need to write the return keyword.
711 |
712 | ```javascript
713 | const myNums = [1,2,3];
714 | const newNums = myNums.filter(num => num > 4)
715 | ```
716 | - When we use curly braces, then we need to use return, as we will start the scope here.
717 | ```javascript
718 | const myNums = [1,2,3];
719 | const newNums = myNums.filter(num=> {
720 | return num > 4;
721 | })
722 | ```
723 | - Consider an array has given with some objects, so we need to apply filters on it.
724 |
725 | #### map():
726 | - It looks better than forEach loop
727 | - It also have a callback
728 | - map automatically return the new array
729 | - Chaining methods: means we can apply multiple methods at once
730 | - Whatever values are passed in chaining it will be passed to respective methods
731 |
732 | #### reduce():
733 | - Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
734 | - Whatever we give the initial value, it goes into accumulator
735 | - Reduce will work on entire array
736 | - In reduce methods, we get 2 parameter, one is accumulator and other is current value
737 | - We can assign the value from which we want to start the value in accumulator
738 |
739 | # ☕ Chai aur Javascript 2
740 |
741 |
742 |
743 | ## Lecture 1: DOM Introduction
744 |
745 | - Congrats! on completion of javascript basics
746 | - For mastering javascript, we need to focus on events and DOM
747 | - Lets focus on DOM Now,
748 | - Create a folder 06_dom ➜ create one.html
749 | - To create the lorem sample 5 words use: lorem5 enter
750 | - DOM is document object model, The webpage is created from object like head, body etc
751 | - DOM tells how the page structure is all about, It also tell the document object is made up of which object, so we can manipulate the page
752 | - If I understand events, then I can understand , on button click, what should be there, should we send the request or not etc
753 | - To see the details of browser method see console.log(window)
754 | - Instead of focusing complex object, it is better to focus on window.document object
755 | - As window.document is so common object, so we can access document object directly as well console.log(document)
756 | - console.dir(document) it will give all the hidden details as well, that were missing using console.log(document)
757 | - will only tell what type of html page it is
758 | - In DOM, everything is node, like head, bodt etc
759 |
760 | 
761 |
762 | - We can go to wiki page, search for Brandan Eich, here we can search of id, firstHeading
763 |
764 | **Example:**
765 | ```javascript
766 | document.getElementById('firstHeading')
767 | ```
768 | - so we will be getting the element of that id.
769 | - we can manipulate the page as below
770 |
771 | ```javascript
772 | document.getElementById('firstHeading').innerHTML = "
Chai aur code"
773 | ````
774 |
775 | - So in this we can add, remove, apply filters to the element in DOM manipulation
776 | - Learn all the above basic rather focusing on any framework
777 |
778 |
779 |
780 |
781 | ## Lecture 2: All DOM Selector
782 |
783 | - Open wiki page of ajavascript, as the wiki page is created so cleanly
784 | - We will see here, what element we can catch, and what the things we can do manipulate it.
785 | - Focus on Javascript rather than react, angular, sevelt, who knows future
786 | - Focus on selecting element then apply methods to manipulate it.
787 | - Behind the scene, document understand it as className not class
788 | - we can get the attibute using:
789 |
790 | ```javascript
791 | document.getElementById('title').getAttribute('id')
792 | ```
793 |
794 | - We should remember not to override the existing attribute
795 | ```javascript
796 | document.getElementById('title').setAttribute('class','test heading')
797 | ```
798 |
799 | - here, new class is test, existing class is heading
800 | - We can set the styling of element as below,
801 |
802 | ```javascript
803 | const title = document.getElementById("title");
804 | title.style.backgroundColor = 'green'
805 | ```
806 |
807 | ### How to add the content
808 | - We will be using textContent, innerHTML, innerText
809 | - **InnerContent vs InnerText:** InnerText will give the text which is visible, but InnerContent will give the text which is hidden as well.
810 | - innerHTML will give the complete value
811 | - In real time, we will be using other query selector, like querySelector, querySelectorAll etc
812 | **Example:**
813 | ```javascript
814 | document.querySlector('h1')
815 | //we will be getting the 1st h1 element
816 | ```
817 | - querySelector is quite similar to jquery
818 | - **Example:**
819 | ```javascript
820 | document.querySelector('#title');
821 | //we can use othe selectors as well, like class selector
822 | document.querySelector('.heading');
823 | // we can select the input slector as well
824 | document.querySlector(input);
825 | //we can select the attribute as well
826 | document.querySelector('input[type="password"]')
827 | //select 1st child of paragraph
828 | document.querySelector('p:first-child');
829 | ```
830 | - Try to use emmet shortcuts, how sir is using,
831 | **Example:** To write 3 list item, use ul>;i*3
832 | - We can select element and manipulate the element as below
833 | **Example:**
834 | ```javascript
835 | const myUl = document.querySelector('ul');
836 | myUl.querySelector('li')
837 | const turnGreen = myUl.querySelector('li')
838 | turnGreen.style.backgroundColor = "green"
839 | turnGreen.style.padding = "10px";
840 | turnGreen.innerText = "five"
841 | ```
842 |
843 | - Remember, querySelector will only gives 1 value
844 | - To select all list item, use querySelectorAll()
845 | - Nodelist are not pure array
846 | ```javascript
847 | const tempLiList = document.querySelectorAll('li');
848 | tempLiList[0].style.color = "green"
849 | // to manipulate whole details, we can use forEach loop
850 | tempLiList.forEach(l=>{
851 | l.style.backgroundColor = 'green'
852 | })
853 | ```
854 | - In querySelectorAll, it is important to know what datatype it is returning
855 | - Scenario: We need to apply class on each element of list
856 | - **Array.from():** This method will convert nodelist into the array
857 | ```javascript
858 | const tempClassList = document.getElementsByClassName('list-item');
859 | Array.from(tempClassList);
860 | ```
861 | ```javascript
862 | const myConvertedArray = Array.from(tempClassList);
863 | myConvertedArray.forEach(function(li){
864 | li.style.color = "orange"
865 | })
866 | ```
867 | - we can manipulate the page value as
868 | ```javascript
869 | const myH2 = document.querySelectorAll('.mw-headline')
870 | myH2.forEach(function(h){
871 | h.style.color = "black"
872 | h.style.backgroundColor = "green"
873 | h.style.color = "white"
874 | h.style.padding = "10px"
875 | h.innerText = "Sarfaraz"
876 | })
877 | ```
878 |
879 |
880 |
881 | ## Lecture 3: How to create a new element
882 |
883 | - Knowledge on DOM will help to crack the interview, so dont take it lightly before starting react
884 | - We will focus here on relations, like parent-child relation, parent-parent relations etc
885 | - Scenario: we need to create the element ➜ create the query from DB ➜ Set into array ➜ display in UI
886 | - Play with DOM to add or remove an element
887 | - to create div with4 elements use shortcut: div.day*4
888 | - Lets check the value in the parent
889 | - parent.children will give the list of html collection
890 | - To select 1 element in array: parent.children[0]
891 | - To access the inner value of it, we can use parent.children[0].innerHTML
892 | - We can create the new element using document.createElement('div'), so here div is created
893 | - The document will be visible when it is attached using appenChild method
894 |
895 |
896 |
897 |
898 | ## Lecture 4: Edit and remove DOM element
899 |
900 | - Remember: Everything declared in function scope is not accessible outside
901 | - Better to use appendChild rather InnerHTML
902 | - There is not much difference between innerHTML and innerContent
903 | - Mentioned everything in comment in the file, practice a bit from w3school for querySelectors
904 |
905 |
906 |
907 |
908 | ## Lecture 5: Lets build 4 Javascript Project
909 |
910 | ### Project 1:
911 |
912 | - Without events, it is not possible to do big projects
913 | - We can view the markup file view in vs code, the short cut is available in the right corner of vscode.
914 | - Go the stackblitz folder, copy html, css file content from
915 | - project 1 Select all the box
916 | - **e.target:** means from which target we got the event
917 |
918 | ### Project 2: BMI Calculator
919 | - From the input form, we need to need to get the value.
920 | - First we need to select the form, as form has submit button.
921 | - Here, we have submit button
922 |
923 | ### Project 3: Digital Clock
924 | - Please learn flexbox in css, as flexbox is used here to center the div
925 | - We need to create the digital clock, which need to be change on every second
926 | - setInterval controls the interval, we set the time, it will run continuesly
927 | **Example:**
928 | ```javascript
929 | //Syntax:
930 | setInterval(function(){}, 1000)
931 | ```
932 |
933 | ### Project 4: Guess the number
934 |
935 | - Generate the random number and guess is it correct or not.
936 | - Random number will give always new value, to get 10 number multiply by 10, add 1 to get number above 0
937 | - To get the number in interger we use parseInt
938 | - We often need to write the validation logic, like, is the number available in DB, is the number is unique etc
939 |
940 |
941 |
942 |
943 | ## Lecture 6: Events in Javascript
944 |
945 | - Whatever the eventd run in the javascript, it runs in sequentially
946 | - But in asynchronous programming, we deviate the sequence and come back, same like browser event, it acitivate in browser events.
947 | - Write a logic that is scalable in javascript, so better avoid writing onclick on button in js.
948 | - Dont write simply onclick event but use addEventListener, as it will give much detail like propogation, or gives less features if use onclick.
949 | - Add the event listener in string.
950 | - We should learn about type, timestamp(how to change the date), preventDefault(to overrid the default value of any tag), target, toElement, srcElement, currentTarget. - Need to know clientX, clientY, screenX, screenY related to positions.
951 | - altKey, ctrlKey, shiftKey, keyCode(what is the key code of any character, or to check keyboard speed).
952 | - Event Propogation is of 2 types, Event bubbling(default), Event capturing.
953 | - If we add the addEventlistener on parent and child, we should think, which will be clicked first?.
954 | - The answer is Event bubbling, means the event propogates from low to high. Here 1st from li then ul.
955 | - If we apply e.stopPropogation, then event will not propogate to the parent.
956 | - **e.target:** it will give the targeted element
957 | - **e.target.parentNode:** Here, we can select the parent element.
958 | - **remove():** It will remove the element from nodeList.
959 | - **removeChild():** It will remove the child element from parent Node.
960 | - Read more about event, that help in understanding the events
961 |
962 |
963 |
964 |
965 | ## Lecture 7: Async code (Theory)
966 |
967 | - We will focus on basic on sync javascript, so that It will be helpful to learn promises, async-await etc
968 | - We should know basics like, Javascript is
969 | 1) Synchronous: Execute one line of code at a time.
970 | 2) Single threaded languge: Work on 1 thread, slow language as compared to other
971 | 3) Execution context: Execute one line of code at a time. Here Each operation waits for the last one to complete before executing
972 | - There are 2 types of code in javascript
973 | 1) Blocking Code: Block the flow of the program ➜ Read the file
974 | 2) Non-Blocking Code:Does not block execution ➜ Read file Async
975 | - It is based on the use case, what code we need to use either blocking or non blocking
976 | - Example for non blocking code, till we store the data in db and get response that entry is done ➜ then give the message to the user that registration is successful or not, then we should go ahead with non blocking operation.
977 | - JS Engine: It is a complete javascript engine, which execute the javascript
978 | - JS Engine is made up of 1) Memory Heap 2) Call stack
979 | - Web API: We will get Web API in browser, we wont get anywhere, we call it in sometime Node environment
980 | - If we consider Node for web API, then we wont get DOM API
981 | - Task queue: Task queue only make the JS engine fast
982 | - Promise has different high priority queue, we call it high priority queue
983 | - How the program executes:
984 | - 1st callstack is created ➜ created the global execution context and one by one function is loaded ➜ whenever work of function is completed, functions are unloaded
985 | - **Memory heap:** here memory is allocated - Async code, we use, we say, yaar do this work and please remember me in future ha, ➜ it is registerd in Register callback, who register all the events
986 | - Async code are like settimeout, setinterval etc Task Queue: Once the task is completed, the register callback send the details to task queue. task queue add to the callback and add back to call stack. Task queue is last in first out.
987 | - fetch is just a high priority call
988 |
989 |
990 |
991 |
992 |
993 | ## Lecture 8: 2 Projects with async
994 |
995 | - We will get the functions like setTimeput, setInterval are functions of window object.
996 | - If we use setTimeout, then after 2 sec, name will be printed only once.
997 |
998 | **Example:**
999 | ```javascript
1000 | setTimeout(function(){
1001 | console.log("Sarfaraz");
1002 | }, 2000)
1003 | ```
1004 | - In settimeinterval, the work will be executed after every specific time interval
1005 | - clearTimeout: we can remove the settimeout function, but cleartimeout seek reference of what timeout need to be removed. ➜ cleartimeout say remove everything for that reference what is there in call stack
1006 | - We will call the clearTimeout on button click
1007 | ```javascript
1008 | document.querySelector('#stop').addEventListener('click',function(){
1009 | clearTimeout(changeMe);
1010 | console.log('Stopped');
1011 | })
1012 | ```
1013 | - We will be getting the name after every 1 sec
1014 | ```javascript
1015 | setInterval(function(){ console.log("Hitesh"); },1000)
1016 | ```
1017 | - We can stop the interval using clearInterval, here clearInterval seek the reference to pass.
1018 | - Here, the scenario is, if we click on start button then start the interval, if we click on stop button, it should stop the interval.
1019 |
1020 | ## Project 6: Unlimited colors
1021 | - Onchange of start button change the background color, after every sec background color should change.
1022 |
1023 |
1024 |
1025 |
1026 | ## Lecture 9: API request and v8 engine
1027 | - API is the talking language
1028 | between 2 systems - famous API is of github
1029 | - To know the basic
1030 | information about github user, Example:
1031 | https://api.github.com/users/hiteshchoudhary
1032 | - format is API, having big
1033 | object having values.
1034 | - other example: https://randomuser.me - We can use
1035 | jsonformatter.org to format the API and check the details in tree format -
1036 | Before fetch method, we use to send the XMLHttpRequest: It is completly
1037 | ajax programming
1038 | - Reference:
1039 | https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest - just for
1040 | knowledge we are ready XMLHttpRequest
1041 | - XMLHttpRequest: we can send or
1042 | recive the data, it is a class - open() method cant be called directly ➜
1043 | if we do send() then we can say it is called.
1044 | - When we talk about current
1045 | context, then we use this
1046 | - Most of the time we get the data, it is in string format
1047 | - **JSON.parse():** It will convert the object from string to JSON.
1048 | - **console.log():** It is browser dev tool, it is not a part of javascript
1049 | - v8 engine gives all the tools of debugging. actual implementation of console.log is available here in v8 engine code.
1050 |
1051 |
1052 |
1053 |
1054 | ## Lecture 10: Promise
1055 |
1056 | - Before understanding the fetch, it is important to learn about promise
1057 | - In javascript, we use less reference to class, everthing we see as an object reference.
1058 | - **Reference:** https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
1059 | - When we do any task in promise, then it will complete now.but it will complete in future.
1060 | - Promise has 3 state:
1061 | - **Pending:** niether fullfilled nor rejected
1062 | - **fullfilled:** means the operation is completed successfully
1063 | - **rejected:** means operation is failed
1064 | - Most of the time, we can see promises are mostly consumed.
1065 | - It is better to create promise then learn how to consume it.
1066 | - Promise itself is an object - with new key we get the new instance.
1067 | - Promises are introduced in ES6
1068 | - Before promise, Q, Bluebird library were used, now this library is integrated in nodejs by default.
1069 | - Promise reduces the callback hell
1070 | - Promise take callback function which take 2 parameters resolve and reject.
1071 |
1072 | - **.then()** has direct connect with resolve, .then() has callback function, it return the value
1073 | - To connect promise with then(), we need to call resolve() method in promise creation.
1074 | - Mostly the data passed is an object in promise.
1075 | - We can use .then().then() this is called chaining, in 2nd then we will get the value what we returned from 1st then.
1076 | - **finally():** It tell, after x amount of time, it is done or not.
1077 | - Promise is in general the thing which will be done in future.
1078 |
1079 | ### Async Await
1080 | - It is like promise concept only, just wait, if work done then only it will proceed else it will give error
1081 | there itself. - Suntax: async await
1082 | - The problem with async- awit, we cant handle the error directly
1083 | - We can use dummy response: https://jsonplaceholder.typicode.com/users
1084 | - If we use fetch(), it will take time, so we need to write await in async function.
1085 | - response.json(): we are saying, hey response convert into json, as the data what we got is in the string format.
1086 |
1087 |
1088 |
1089 |
1090 | ## Lecture 11: fetch (Theory)
1091 |
1092 | - fetch is a method in nodejs
1093 | - Blog Reference: https://blog.logrocket.com/fetch-api-node-js/
1094 | - Back then we were using XMLHttpRequest, but it was very hard to implement with other libraries like jquery etc.
1095 | - Fetch API was available but not included in nodejs environment, as fetch api was heavily dependent on browser.
1096 | - We can stop the node request using abortController.
1097 | - So now onwards all async calls will be done using fetch only.
1098 | - fetch is a global mothod which start the process to fetch the resource from a network. It return the promise
1099 | - Reference: https://developer.mozilla.org/en-US/docs/Web/API/fetch
1100 |
1101 | 
1102 |
1103 | - Special queue is created for fetch in event loop or called as "Micro task queue or Priority queue or fetch queue", It is VIP line.
1104 | - fetch works in 2 parts
1105 | 1) Web browser: Here nodejs add the feature of brower, It will handle the web API ➜ From it will call the network request ➜ either we will get the date then it goes to onfulfilled or if no data found it goes to onRejection.
1106 | 2) Data: To reserve the memory space, we may call data, other is arrays, onFulfilled, onRejection. We can't access those arrays. These are private field.
1107 | - Initially data is empty
1108 | - Its data's responsibility to fullfill the memory
1109 |
1110 | ## ------------------------ Classes & Objects : (bit theory) ------------------------
1111 |
1112 | ## Lecture 12: Object Oriented Javascript
1113 | - Technically javascript is not having class but yes javascript does have classes. class is afeature of ES6.
1114 | - We should use chatGPT while working in javascript or react.
1115 | - Javascript is a prototyped based language, it is syntactic sugar over existing prototype based inheritance mechanism.
1116 |
1117 | ### Object literal:
1118 | - Create the object literally
1119 | ```javascript
1120 | const user = {
1121 | username : "Hitesh",
1122 | loginCount: 8,
1123 | signedIn : true
1124 | } //we can access using dot or [] notation
1125 | user["username"];
1126 | ```
1127 | - Object is a collection of properties and methods
1128 | - With the help of new keyword, we can create multiple instances, And we call it as constructor function.
1129 | - the left hand side shows the variable name and right side shows the value.
1130 | - When we use new keyword, empty object is created.
1131 | - Constrcutor function is called on new call
1132 | - this keyword is injected
1133 |
1134 |
1135 |
1136 |
1137 | ## Lecture 13: Magic of Prototype: Js Behind the scene
1138 | - Here, we will understand the prototype, which help to understand the internals of javascript - Prototype is the behaviour
1139 | - We will look into new keyword, what is the behaviour of function
1140 | ```javascript
1141 | const newHero = ["Hulk","spiderman"]
1142 | console.log(newHero);
1143 | ```
1144 | - Here, when we console the output, we not only get the array element but we get the Prototype keyward as well, we will explore it more.
1145 | - Javascript is prototypal inheritance: Javascript search at the top till it gets null value.This is prorypal behaviour of javascript
1146 | - Due to prototype bahviour only, we get new keyward, classes and this key works due to this.
1147 | - Everything in javascript is Object, Object is no parent ➜ Object has null reference
1148 | - Srting, Array redirect to object, means it is object.
1149 | - Function is a function as well as it is object in javascript
1150 | - From 'this', we set the current context
1151 | - **prototype:** it gives not only methods but also gives some proprties as well.
1152 | - All about 'new' keyword:
1153 | - **new** keyword initiate the creation of a new javascript object
1154 | - newly created object is linked to constructor's prototype ➜ then constructor is called ➜ finally we get the new object
1155 | - Everything goes through object
1156 | - In Prototypal inheritance we say that how can we access other's properties.
1157 | ```javascript
1158 | //modern syntax of prototypal inheritance
1159 | //copy the details of TeachingSupport ➜ into Teacher
1160 | Object.setPrototypeOf(TeachingSupport, Teacher)
1161 | ```
1162 | - Whoever is called, it is having this reference
1163 |
1164 |
1165 |
1166 |
1167 | ## Lecture 14: Call and this
1168 | - Earlier we were using bind in reactjs version 1, as library was not so defined
1169 | - When there is global context, then this reference to window object while node refere to emoty object
1170 | - call: it is a method to call another method, it pass the current execution context to another function.
1171 | - call method used to call the reference, here this gives the current context.
1172 |
1173 |
1174 |
1175 |
1176 | ## Lecture 15: Class and constructor
1177 | - **class** is the keyword in javascript
1178 | - Behind the scene of classes, it is simply a function with some protypal properties and methods
1179 | - We can extends the properties using 'extends' keyword
1180 | - 'static': it is a keyword which restrict to access, as like we want to restrict not to give unique id everytime for everyone.
1181 |
1182 |
1183 |
1184 |
1185 | ## Lecture 16: Bind
1186 | - **bind** is used in eary version of reactjs
1187 | - Bind says about attachment
1188 | - Through bind, we can have access for everything related to that function.
1189 |
1190 |
1191 |
1192 |
1193 |
1194 | ## Lecture 17: Now you know Objects
1195 |
1196 | - Object has so many properties
1197 | ```javascript
1198 | const mynewObj = {username: "sarfaraz"}
1199 | mynewObj;
1200 | ```
1201 | - getOwnPropertyDescriptor: It gives the internal properties of object details
1202 | **Example:**
1203 | ```javascript
1204 | Object.getOwnPropertyDescriptor(Math)
1205 | ```
1206 | - Can we change the value of object property? Yes we can using Object.defineProperty
1207 | ```javascript
1208 | const chai = {
1209 | name: "ginger chai",
1210 | price: 250,
1211 | isAvailable: true,
1212 |
1213 | orderChai: function(){
1214 | console.log("Chai nahi bani");
1215 | }
1216 | }
1217 |
1218 | console.log(Object.getOwnPropertyDescriptor(chai, "name"));
1219 |
1220 | //which property to change
1221 | Object.defineProperty(chai, 'name',{
1222 | writable: false,
1223 | enumerable: false,
1224 | })
1225 |
1226 | console.log(Object.getOwnPropertyDescriptor(chai, "name");
1227 | ```
1228 | - Object is not iteratable by default, we can make object iterable using Object.entries
1229 |
1230 |
1231 |
1232 |
1233 | ## Lecture 18: Getters and setters
1234 |
1235 | - Suppose, we dont want to give the property of class, then we can use getter and setters.
1236 | - it is compulsory to setter and if getter is written
1237 | - getter helps to get the value
1238 | - It is better to create a property by using undescore to avoid the setter, getter race condition
1239 | - Function behave in 2 ways, one is function and other is object.
1240 | - **Object.defineProperty:** it is a property of getter and setter property, Old code before classes it is used in function.
1241 | - We need to write setters and getter, so that others cant access it.
1242 | - here underscore **_** define the private property, cant be used by normal user.
1243 |
1244 |
1245 |
1246 |
1247 |
1248 | ## Lecture 19: Lexical scope and closure
1249 |
1250 | - **Closure Reference:** https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
1251 | - Closure gives you access to an outer function's scope from an inner function.
1252 | - If the outer function has inner function then at this time memory is shared.
1253 | - The variable decalred in outer function has access in both outer and inner function.
1254 | - It is not possible to access the variable declared inside function to outside of function.
1255 | - While we return the function reference, we return the whole lexical scope, means it return the variable as well.
1256 |
1257 |
1258 |
1259 |
1260 | ## Lecture 20: Javascript ends with story
1261 |
1262 | - When you do project ➜ you stuck ➜ you solve ➜ you only learn
1263 |
--------------------------------------------------------------------------------