├── Ch 1 Practice Set.js ├── Ch 1 Variable.js ├── Ch 10 Network Request And Storing Data.js ├── Ch 11 Object Oriented Programing.js ├── Ch 12 Advanced JavaScript.js ├── Ch 2 Expression & Conditional Statement Practice Set.js ├── Ch 2 Expression & Conditional Statement.js ├── Ch 3 Loops And Functions Practice Set.js ├── Ch 3 Loops And Functions.js ├── Ch 4 String Practice Set.js ├── Ch 4 String.js ├── Ch 5 Array Practice Set.js ├── Ch 5 Array.js ├── Ch 6 JS In Browser.js ├── Ch 6 JavaScript In Browser Practice Set.js ├── Ch 6 JavaScript In Browser.js ├── Ch 7 DOM Part 1.js ├── Ch 7 DOM Part 2.js ├── Ch 7 DOM Practice Set.js ├── Ch 7 Js DOM.js ├── Ch 8 Event & Other DOM Properties.js ├── Ch 8 Events And Other DOM Properties.js ├── Ch 9 Callbacks, Promises And Async And Await.js ├── Ch-10-Network-Request-And-Storing-Data.zip ├── Ch-10-Network-Request-And-Storing-Data ├── .gitignore ├── Readme.md ├── image.png ├── index.html ├── script.js └── style.css ├── Ch-11-Object-Oriented-Programing.zip ├── Ch-11-Object-Oriented-Programing ├── .gitignore ├── Readme.md ├── image.png ├── index.html ├── script.js └── style.css ├── Ch-12-Advanced-JavaScript.zip ├── Ch-12-Advanced-JavaScript ├── .gitignore ├── Readme.md ├── index.html ├── script.js └── style.css ├── Ch-4-String.zip ├── Ch-4-String ├── Readme.md └── index.js ├── Ch-6-JS-In-Browser.zip ├── Ch-6-JS-In-Browser ├── .gitignore ├── index.html ├── script.js └── style.css ├── Ch-7-Js-DOM.zip ├── Ch-7-Js-DOM ├── .gitignore ├── Readme.md ├── image.png ├── index.html ├── script.js └── style.css ├── Ch-8-Events-And-Other-DOM-Properties.zip ├── Ch-8-Events-And-Other-DOM-Properties ├── .gitignore ├── Readme.md ├── index.html ├── script.js └── style.css ├── Ch-9-Callbacks-Promises-And-AsyncAwait.zip ├── Ch-9-Callbacks-Promises-And-AsyncAwait ├── .gitignore ├── Readme.md ├── image.png ├── index.html ├── script.js └── style.css └── README.md /Ch 1 Practice Set.js: -------------------------------------------------------------------------------- 1 | //Ch 1 Variable -> Practice Set 2 | 3 | // Q1) Create a Variable of Type String And try To Add a Number To It. 4 | 5 | 6 | let a = "Darshan"; 7 | let b = 10; 8 | 9 | console.log(a + b); 10 | 11 | // Output: Darshan10 12 | 13 | 14 | // Q2) Use typeof Operator To Find Data-type of the First Question of the Last Answer. 15 | 16 | 17 | console.log(typeof (a + b)); 18 | 19 | // Output: String 20 | 21 | 22 | // Q3) Create a Const Object in JavaScript. Can You Change It to Hold A Number Latter? 23 | 24 | 25 | const c = { 26 | name: "Darshan", 27 | author: "CrptoMinds", 28 | isPrincipal: false 29 | } 30 | 31 | c = 1; 32 | // Output: Assignment to Constant Variable -> Ans Is No 33 | 34 | 35 | // Q4) Try To Add a New Key In Q3 Const Object. Were You Able To Do It? 36 | 37 | 38 | const c1 = { 39 | name: "Darshan", 40 | author: "CrptoMinds", 41 | isPrincipal: false 42 | } 43 | 44 | c1['friend'] = "Krupali"; 45 | 46 | //const c1 -> Point Object -> We Can Change Value Inside The Object -> We Can't Make New c1 Objact Again -> Because Of Constant 47 | console.log(c1); 48 | 49 | // Output: 50 | // { 51 | // name: 'Darshan', 52 | // author: 'CrptoMinds', 53 | // isPrincipal: false, 54 | // friend: 'Krupali' 55 | // } 56 | 57 | 58 | // Q4) Write A JS Program To Create a Word-Meaning Dictionary Of 5 Words. 59 | 60 | 61 | const dict = { 62 | appreciate: "recognize the full worth of ", 63 | ataraxia: "a state of freedom from emotional disturbance", 64 | yakka: "Work, especially hard work." 65 | 66 | } 67 | 68 | console.log(dict.yakka); 69 | console.log(dict['yakka']); 70 | 71 | // Output: Work, especially hard work. 72 | // Work, especially hard work. -------------------------------------------------------------------------------- /Ch 1 Variable.js: -------------------------------------------------------------------------------- 1 | // Variable Declaration: 2 | // To declare a variable in JavaScript: 3 | // Before ES6 -> var was used -> After ES6 -> let is used 4 | // const is used to define constant -> throughout the program value not changed 5 | 6 | // Let, Const -> Used To Block Scope Variable Declaration 7 | // Var -> Globally Scoped 8 | // Let Can Be Updated But Not Re-declared 9 | //Const -> Neither Updated Nor Re-declared 10 | // Var -> Can Be Updated And Re-declared 11 | // Var & Let Is Initialized With Undefined -> Const Are Not 12 | var dp; 13 | let ap; 14 | const hp; //Error 15 | 16 | var myVariable; // Declaration using var 17 | let anotherVariable; // Declaration using let 18 | const PI = 3.14159; // Declaration using const 19 | 20 | // JS is Case Sensitive 21 | 22 | // You can also declare and assign a value to a variable in a single line. 23 | 24 | //JavaScript Data-Type 25 | //Object Is Non Primitive Data-Type 26 | // Primitive -> Null, Number, String, Symbol, Undefined, Boolean, Bigint -> Fundamental Data-Type -> nn bb ss u 27 | 28 | 29 | let y = BigInt("265"); 30 | let x = Symbol("I Am Symbol"); 31 | let s = null; //Define Null 32 | 33 | // Type 34 | console.log(typeof x); 35 | 36 | //Object -> In Python -> Dictionary 37 | //ES6 -> ECMAScript -> Modern JavaScript 38 | const item = { 39 | name: "CryptoMinds", 40 | age: "12" 41 | //Key: Value 42 | } 43 | 44 | console.log(item["age"]); //Look Up 45 | 46 | //Scope -> Alt + Click -> Multiple Cursor In Replit 47 | //var 48 | 49 | var b = 11; 50 | var b = 13; // Allow To Use 51 | 52 | { 53 | var b = 15; 54 | console.log(b); 55 | } 56 | console.log(b); 57 | 58 | //Output 59 | // 15 60 | // 15 61 | 62 | //let 63 | 64 | let b = 11; 65 | 66 | { 67 | let b = 15; 68 | console.log(b); 69 | } 70 | console.log(b); 71 | 72 | //Output 73 | // 15 74 | // 11 75 | 76 | 77 | let c = 16; 78 | c = 17; //Update 79 | 80 | 81 | let d = 16; 82 | let d = 17; //Error 83 | 84 | 85 | 86 | 87 | 88 | 89 | var myNumber = 42; 90 | let myString = "JavaScript"; 91 | const myConstant = true; 92 | 93 | // Variable Naming: 94 | // JavaScript variable names can include letters, digits, underscores, and dollar signs. They must start with a letter, underscore, or dollar sign (but not a digit). JavaScript is case-sensitive, so myVariable and myvariable are considered different variables. 95 | 96 | var firstName; 97 | let age; 98 | const PI = 3.14; 99 | 100 | 101 | 102 | // Better Practice to use let and Const 103 | // Mostly Use Const 104 | // JS Allow to Change Variable Type In Run Time -> Only One 105 | 106 | 107 | function myFunction() { 108 | var x = 10; // Function-scoped variable 109 | if (x > 5) { 110 | let y = 20; // Block-scoped variable 111 | console.log(x + y); 112 | } 113 | console.log(x); // Accessible 114 | console.log(y); // Error: y is not defined 115 | } 116 | 117 | 118 | // Variable Hoisting: 119 | // JavaScript has a concept called "hoisting," where variable and function declarations are moved to the top of their respective scopes during the compilation phase. Variables declared with var are hoisted but are not initialized until the line where they are defined. This can sometimes lead to unexpected behavior. 120 | 121 | 122 | console.log(x); // Undefined 123 | var x = 10; 124 | 125 | 126 | // Variable Constants: 127 | // Variables declared with const are constants, meaning their value cannot be reassigned once it is set. However, it's important to note that const does not make objects or arrays immutable. It only prevents the reassignment of the variable itself. 128 | 129 | 130 | const PI = 3.14; 131 | PI = 3.14159; // Error: Assignment To Constant Variable 132 | 133 | const myArray = [1, 2, 3]; 134 | myArray.push(4); // Valid, Since The Array Itself Is Mutable 135 | 136 | // Conclusion: 137 | // JavaScript variables play a crucial role in storing and manipulating data within a program. By understanding variable declaration, assignment, naming, scope, and the differences between var, let, and const, developers can effectively work with variables to create dynamic and interactive JavaScript applications. -------------------------------------------------------------------------------- /Ch 10 Network Request And Storing Data.js: -------------------------------------------------------------------------------- 1 | // Fetch API 2 | // The Fetch API provides a simple way to fetch resources (for example images, documents, or streams) over the internet 3 | 4 | // JavaScript Can Be Used To Send And Retrieve Information From The Network When Needed (AJAX) 5 | 6 | // AJAX Used Earlier -> Now JSON Is Widely Used 7 | 8 | // AJAX -> Asynchronous JavaScript And XML 9 | 10 | // Fetch API 11 | 12 | // Fetch Is Used To Get Data Over The Internet 13 | 14 | // let promise = fetch(URL, [options]) 15 | // Without Option A GET Request Is Sent 16 | 17 | // Getting The Response Is A 2-Stage Process 18 | 19 | // 1. An Object Of Response Class Containing "Status" And "Ok" Properties 20 | // Status - The HTTP Status Code, eg 200 21 | // Ok - Boolean, True If The HTTP Status Code Is 200-299 22 | 23 | // 2. After That We Need To Call Another Method To Access The Body In Different Formats 24 | 25 | // Response.text() - Read The Response As Text 26 | // Response.json() - Parse The Response As JSON 27 | 28 | // Other Methods Include - Response.formData(), Response.blob(), Response.arrayBuffer() 29 | 30 | // Note - We Can Use Only One Body Method. For Example If We Have Used Response.text() Then We Cannot Use Response.json() 31 | 32 | // Response Headers 33 | 34 | // The Response Headers Are Available In Response.headers 35 | 36 | // Request Headers 37 | // To Set A Request Header In Fetch, We Can Use The Headers Option 38 | 39 | // let res = fetch(url, { 40 | // header: { 41 | // Authentication: 'Secret' 42 | // } 43 | // }); 44 | 45 | 46 | // POST Request 47 | 48 | // let p = fetch("https://api.rainviewer.com/public/weather-maps.json") 49 | // p.then((response) => { 50 | // console.log(response.status) 51 | // console.log(response.ok) 52 | // console.log(response.headers) 53 | // return response.json() 54 | // }).then(data => { 55 | // console.log(data) 56 | // }) 57 | // Why Two .then Is Mentioned Above? 58 | // Response Contain Two Properties - Status And Ok 59 | // Data Is The Actual Result Of The Request 60 | 61 | // POST Request 62 | // To Make Post Request, We Need To Use Fetch Options 63 | // Method -> HTTP Method, E.g POST 64 | // Body -> The Request Body 65 | 66 | // const createTodo = async (todo) => { 67 | // let options = { 68 | // method: "POST", 69 | // headers: { 70 | // "Content-type": "application/json" 71 | // }, 72 | // body: JSON.stringify(todo), 73 | // } 74 | // let p = await fetch('https://jsonplaceholder.typicode.com/posts', options) 75 | // let response = await p.json() 76 | // return response 77 | // } 78 | 79 | // const getTodo = async (id) => { 80 | // let response = await fetch('https://jsonplaceholder.typicode.com/posts/' + id) 81 | // let r = await response.json() 82 | // return r 83 | // } 84 | 85 | // const mainFunc = async () => { 86 | // let todo = { 87 | // title: 'Harry2', 88 | // body: 'bhai2', 89 | // userId: 1100, 90 | // } 91 | // let todor = await createTodo(todo) 92 | // console.log(todor) 93 | // console.log(await getTodo(101)) 94 | // } 95 | 96 | // mainFunc() 97 | 98 | // let response = await fetch('/url', { 99 | // method: 'POST', 100 | // headers: { 101 | // 'Content-Type': 'application/json' 102 | // }, 103 | // body: JSON.stringify({ 104 | // title: 'foo', 105 | // body: 'bar', 106 | // userId: 1, 107 | // }) 108 | // }) 109 | 110 | // let result = await response.json() 111 | 112 | // JavaScript Cookies 113 | // Cookies Are Small Strings Of Data Stored By The Client Side Stored In Browser 114 | // In JavaScript, Document.cookie Property Can Be Used To Access Cookies 115 | 116 | // Cookies Are Set By Web Server Using Set-Cookie HTTP Header. Next Time When The Request Is Sent To The Same Domain, The Browser Sends The Cookie Using Cookie HTTP Header In The Request. That Way The Server Knows Who Sent The Request. 117 | 118 | // We Can Also Access Cookies Using document.cookie Property 119 | // alert(document.cookie) -> Contain Key Value Pairs Decoded 120 | 121 | // Key Value Pair Are Separated By Delimited By ; -> Key = Pair; 122 | 123 | // Writing A Cookie 124 | // An Assignment To Document.cookie Is Treated Specially In A Way That Write Operation Doesn't Touch Other Cookie 125 | 126 | // document.cookie = "name=harry1122334400" 127 | // Updates Only Cookie Named User To Harry 128 | 129 | // Bahot Chota Sa Data Store Karneka Tarika 130 | // console.log(document.cookie) 131 | // document.cookie = "name=harry1122334400" 132 | // document.cookie = "name2=harry11223344002" // Set Call 133 | // document.cookie = "name=harry" // Old Is Updated 134 | // let key = prompt("enter your key") 135 | // let value = prompt("enter your value") 136 | // document.cookie = `${encodeURIComponent(key)}=${encodeURIComponent(value)}` 137 | // console.log(document.cookie) 138 | 139 | // Encode URI Component -> This Function Encodes A Set Of Special Characters In A Way That The Component Can Be Decoded Using DecodeURI 140 | 141 | // This Function Helps Keep The Valid Formatting. It Is Used Like This 142 | 143 | // document.cookie = `${encodeURIComponent(key)}=${encodeURIComponent(value)}` 144 | 145 | // This Way Spacial Character Are Encoded 146 | 147 | // Cookies Option 148 | 149 | // Cookies Have Several Options Which Can Be Provided After Key=Value To A Set Call Like This : 150 | 151 | // document.cookie = "user=harry;path=/a;expires=Tue,29 March 204" 152 | // path -> Which Domain The Cookie Will Be Available On 153 | // document.cookie = "user=harry;path=/a;expires=Tue,29 March 2041 12:00:33 GMT" 154 | // Set Only One Cookies With Path And Expires 155 | // document.cookies -> Can Set Only One Cookie At A Time Other Are Option 156 | 157 | 158 | // Path Option Makes The Cookie Available Only At The /a and /a/b ................ Path. -> Not Available At /b But Available At /a/b 159 | // Expires At -> Date When Cookie Will Be Expired. Time Stamp In GMT 160 | 161 | // Note : 162 | // 1. The Name And Value Pair After EncodeURI Component Can Be Up To 4KB 163 | // 2. Total No Of Cookies Per Domain Is Limited To Arbitrary Number Around 20+ (Exact Number Is Browser Dependent) 164 | // 3. Cookies Are Sent With Each Request To The Server, So The Server Can Learn Who Sent The Request 165 | 166 | // Local Storage 167 | // Local Storage Is Web Storage Object Which Are Not Sent To Server With Each Request 168 | // Data Survives Page Refresh And Even After Full Restart 169 | 170 | // These Are Method Provided By Local Storage 171 | 172 | // 1. localStorage.setItem(key, value) -> Store Key Value Pair Or Update The Value If Key Is Already Present 173 | // 2. localStorage.getItem(key) -> Get The Value By Key 174 | // 3. localStorage.removeItem(key) -> Remove The Key Value Pair 175 | // 4. localStorage.clear() -> Clear The Entire Local Storage 176 | // 5. localStorage.key(index) -> Get The Key On A Given Position 177 | // 6. localStorage.length -> The Number Of Stored Items 178 | // We Can Use Both Key And Value As String 179 | 180 | // let key = prompt("Enter key you want to set") 181 | // let value = prompt("Enter value you want to set") 182 | 183 | // localStorage.setItem(key, value) 184 | 185 | // console.log(`The value at ${key} is ${localStorage.getItem(key)}`) 186 | 187 | // if (key == "red" || key == "blue") { 188 | // localStorage.removeItem(key) 189 | // } 190 | 191 | // if (key == 0) { 192 | // localStorage.clear() 193 | // } 194 | // console.log(localStorage.length) 195 | 196 | // We Can Get And Set Values Like An Object 197 | // localStorage.one = 1 198 | // alert(localStorage.one) 199 | // delete localStorage.one 200 | 201 | // Note: 202 | // 1. Both Key And Value Must Be String 203 | // 2. We Can Use The Two JSON Methods To Store Objects In Local Storage 204 | 205 | // JSON.stringify(object) -> Converts Objects To JSON Strings 206 | // JSON.parse(string) -> Converts String To Objects (Must Be Valid JSON) 207 | 208 | // Session Storage 209 | // Session Storage Exists For Only One Session. Data Survives Refresh But Not Close Of Browser 210 | 211 | // Used Less As Compared To Local Storage 212 | // Properties And Method Are Same As Local Storage But: 213 | // 1. Session Storage Data Survives Page Refresh But Not Close Of Browser 214 | // It Exists Only Within The Current Browser Tab. Another Tab With Same Page Will Have Empty Session Storage 215 | 216 | // 2. The Data Survives Page Refresh, But Not Closing / Opening Of Browser 217 | 218 | // Storage Event 219 | // When The Data Gets Updated In Local Storage Or Session Storage, Storage Event Triggered With These Properties: 220 | // 1. key -> The Key 221 | // 2. oldValue -> Previous Value 222 | // 3. newValue -> New Value 223 | // 4. url -> Page URL 224 | // 5. storageArea -> local or session 225 | 226 | // We Can Listen The OnStorage Event Of Window Which Is Triggered When Updates Are Made To The Same Storage From Other Documents 227 | 228 | // sessionStorage.getItem("name") 229 | // sessionStorage.clear() 230 | // sessionStorage.removeItem("name") 231 | // sessionStorage.setItem("name", "harry") 232 | // sessionStorage.removeItem("name") 233 | 234 | // Dusri Tab Dusra Page Different Session Storage 235 | 236 | // window.onstorage = (e) => { 237 | // alert("changed") 238 | // console.log(e) 239 | // } 240 | 241 | // Practice Set 242 | 243 | // Q1 Use a Free API From The Internet And Feed Your App With Live Data 244 | 245 | // Q2 Create A Note Saving App Which Stores Your Note To localStorage 246 | 247 | // Q3 Repeat Q2 And Fetch The Note Which User Entered In The Previous Question 248 | 249 | // Q4 Delete The Note In The Previous Question 250 | 251 | 252 | let url = "https://kontests.net/api/v1/all" 253 | let response = fetch(url) 254 | response.then((v) => { 255 | return v.json() 256 | }).then((contests) => { 257 | console.log(contests) 258 | ihtml = "" 259 | for (item in contests) { 260 | console.log(contests[item]) 261 | ihtml += ` 262 |
263 | ... 264 |
265 |
${contests[item].name}
266 |

Status is ${contests[item].status} and site is ${contests[item].site}

267 |

In 24 Hours? ${contests[item].in_24_hours}

268 |

Starts at: ${contests[item].start_time} 269 |

Starts at: ${contests[item].end_time} 270 | Visit Contest 271 |

272 |
273 | ` 274 | } 275 | cardContainer.innerHTML = ihtml 276 | }) 277 | 278 | /* ******************* NOTES APP (REMAINING QUESTIONS OF PRACTICE SET) *********** */ 279 | // let n = localStorage.getItem("note") 280 | // alert("Your note is " + n) 281 | 282 | // let a = prompt("Enter your note") 283 | // if (a) { 284 | // localStorage.setItem("note", a) 285 | // } 286 | 287 | // let c = confirm("Do you want to delete your note?") 288 | // if (c) { 289 | // localStorage.removeItem("note") 290 | // alert("Note deleted successfully!") 291 | // } 292 | -------------------------------------------------------------------------------- /Ch 11 Object Oriented Programing.js: -------------------------------------------------------------------------------- 1 | // [[Prototype]] 2 | // First Priority Object Method Ki Than Nahi Mila To Prototype Ka Method Use Karo 3 | // JavaScript Object Have A Special Property Called Prototype That Is Either Null Or Reference To Another Object 4 | 5 | // When We Try To Read A Property From An Object And It's Missing, JavaScript Will Take It From Its Prototype. This Is Called Prototypal Inheritance. 6 | 7 | // let a = { 8 | // name2: "Harry", 9 | // language: "JavaScript", 10 | // run: () => { 11 | // alert("self run") 12 | // } 13 | // } 14 | // console.log(a) 15 | 16 | 17 | // let p = { 18 | // run: () => { 19 | // alert("run") 20 | // } 21 | // } 22 | 23 | // p.__proto__ = { 24 | // name: "Jackie" 25 | // } 26 | 27 | // a.__proto__ = p 28 | // a.run() 29 | // console.log(a.name) 30 | 31 | // Setting Prototype 32 | // We Can Set Prototype By Setting __proto__ Property On Any Object. Now If We Read A Property From That Object, JavaScript Will Take It From The Object Itself And If It's Missing, JavaScript 33 | 34 | // If We Have A Method In Object, It Will Be Called From Object. If Its Missing In Object And Present In Prototype, It Will Be Called From Prototype. 35 | 36 | // Classes And Objects 37 | 38 | // In OOP A Class Is An Extensible Program Code Template For Creating Objects, Providing Initial Value For State (Member Variables) And Implementation Of Behavior (Member Functions) 39 | 40 | // Syntax: 41 | // class ClassName { 42 | // constructor() { 43 | // // initialise 44 | // } 45 | // // Function 46 | // method_name() { 47 | // // code 48 | // } 49 | // } 50 | 51 | // class RailwayForm { 52 | // submit() { 53 | // alert(this.name + ": Your form is submitted for train number: " + this.trainno) 54 | // } 55 | // cancel() { 56 | // alert(this.name + ": This form is cancelled for train number: " + this.trainno) 57 | // } 58 | // fill(givenname, trainno) { 59 | // this.name = givenname 60 | // Object Associated Property = Input Me A Rahi Value 61 | // this.trainno = trainno 62 | // } 63 | // } 64 | 65 | // // Create a form for Harry 66 | // let harryForm = new RailwayForm() 67 | // // Fill the form with Harry's details 68 | // harryForm.fill("Harry", 145316) 69 | 70 | // // Create a forms for Rohan 71 | // let rohanForm1 = new RailwayForm() 72 | // let rohanForm2 = new RailwayForm() 73 | // // Fill the forms with Rohan's details 74 | // rohanForm1.fill("Rohan", 222420) 75 | // rohanForm2.fill("Rohan", 2229211) 76 | 77 | // harryForm.submit() 78 | // rohanForm1.submit() 79 | // rohanForm2.submit() 80 | // rohanForm1.cancel() 81 | 82 | // We Can Than Use New Class() To Create An Object 83 | 84 | // Constructor Method 85 | // A Constructor Is A Special Method Which Is Automatically Called When An Object Is Created. -> Its Used To Initialize The Object. 86 | 87 | // Old 88 | 89 | // class RailwayForm { 90 | // constructor(givenname, trainno) { 91 | // console.log("CONSTRUCTOR CALLED..." + givenname + " " + trainno) 92 | // this.name = givenname 93 | // this.trainno = trainno 94 | // } 95 | 96 | // submit() { 97 | // alert(this.name + ": Your form is submitted for train number: " + this.trainno) 98 | // } 99 | // cancel() { 100 | // alert(this.name + ": This form is cancelled for train number: " + this.trainno) 101 | // } 102 | // } 103 | 104 | // // Create & fill a form for Harry 105 | // let harryForm = new RailwayForm("Harry", 145316) 106 | // // No need to Fill the form with Harry's details 107 | // // harryForm.fill() 108 | 109 | // // Create & fill a forms for Rohan 110 | // let rohanForm1 = new RailwayForm("Rohan", 222420) 111 | // let rohanForm2 = new RailwayForm("Rohan", 2229211) 112 | 113 | 114 | 115 | // harryForm.submit() 116 | // rohanForm1.submit() 117 | // rohanForm2.submit() 118 | // rohanForm1.cancel() 119 | 120 | // New 121 | 122 | // class RailwayForm { 123 | // constructor(givenname, trainno, address) { 124 | // console.log("CONSTRUCTOR CALLED..." + givenname + " " + trainno) 125 | // this.name = givenname 126 | // this.trainno = trainno 127 | // this.address = address 128 | // } 129 | 130 | // preview() { 131 | // alert(this.name + ": Your form is for Train number: " + this.trainno + " and your address is " + this.address) 132 | // } 133 | 134 | // submit() { 135 | // alert(this.name + ": Your form is submitted for train number: " + this.trainno) 136 | // } 137 | 138 | // cancel() { 139 | // alert(this.name + ": This form is cancelled for train number: " + this.trainno) 140 | // this.trainno = 0 141 | // } 142 | // } 143 | 144 | // let harryForm = new RailwayForm("Harry", 13488, "420, Pacific Ocean, Ocean, Bihar - 0000555") 145 | // harryForm.preview() 146 | // harryForm.submit() 147 | // harryForm.cancel() 148 | // harryForm.preview() 149 | 150 | 151 | // Class Inheritance 152 | 153 | // Class Inheritance Is A Way For One Class To Inherit All The Methods And Properties From Another Class. In JavaScript, It Is Done By Using Extends Keyword. 154 | 155 | // class Animal { 156 | // constructor(name, color) { 157 | // this.name = name 158 | // this.color = color 159 | // } 160 | // run() { 161 | // console.log(this.name + " is running!") 162 | // } 163 | // shout() { 164 | // console.log(this.name + " is barking!") 165 | // } 166 | // } 167 | 168 | // class Monkey extends Animal { 169 | // eatBanana() { 170 | // console.log(this.name + " is eating banana") 171 | // } 172 | // hide() { 173 | // console.log(`${this.name} is hiding`) 174 | // } 175 | // } 176 | 177 | // let ani = new Animal("Bruno", "white") 178 | // let m = new Monkey("Chimpu", "orange") 179 | 180 | // ani.shout() 181 | // m.eatBanana() 182 | // m.hide() 183 | // // ani.hide() //This will throw an error 184 | 185 | // Extend Keyword 186 | 187 | // Extend Keyword Is Used To Extend Another Class. 188 | 189 | 190 | // Class Child extends Parent 191 | 192 | // Parent Classes Is The Class From Which Other Class Inherits. 193 | // class Animal { 194 | // constructor(name, color) { 195 | // this.name = name 196 | // this.color = color 197 | // } 198 | // run() { 199 | // console.log(this.name + " is running") 200 | // } 201 | // shout() { 202 | // console.log(this.name + " is shouting") 203 | // } 204 | // } 205 | // // Child Class 206 | // class Monkey extends Animal { 207 | // eatBanana() { 208 | // console.log(this.name + " is eating banana") 209 | // } 210 | // } 211 | 212 | // Method Overriding 213 | // Method Overriding Is A Feature In OOP Language Where A Child Class Can Override A Parent Method. 214 | 215 | // class Employee { 216 | // constructor(name) { 217 | // console.log(`${name} - Employee's constructor is here`) 218 | // this.name = name 219 | // } 220 | // login() { 221 | // console.log(`Employee has logged in`); 222 | // } 223 | 224 | // logout() { 225 | // console.log(`Employee has logged out`); 226 | // } 227 | 228 | // requestLeaves(leaves) { 229 | // console.log(`Employee has requested ${leaves} leaves - Auto approved`) 230 | // } 231 | // } 232 | 233 | // class Programmer extends Employee { 234 | // constructor(name) { 235 | // super(name) 236 | // console.log(`This is a newly written constructor`) 237 | // } 238 | // // constructor(...args){ ---> If there is no constructor in the child class, this is created automatically 239 | // // super(...args) 240 | // // } 241 | // requestCoffee(x) { 242 | // console.log(`Employee has requested ${x} coffees`) 243 | // } 244 | // requestLeaves(leaves) { 245 | // super.requestLeaves(4) 246 | // console.log("One extra is granted") 247 | // // console.log(`Employee has requested ${leaves + 1} leaves (One extra)`) 248 | 249 | // } 250 | // } 251 | 252 | // let e = new Programmer("Harry") 253 | // e.login() 254 | // e.requestLeaves(3) 255 | 256 | // If We Create Our Own Implimentstion Of Run Method In Child Class, It Will Be Overridden. 257 | 258 | // Super Kewword 259 | // Super Keyword Is Used To Call The Parent Class Constructor. 260 | // When We Override A Method In Child Class, We Use Super Keyword To Call The Parent Class Method. 261 | 262 | // super(a,b) -> Call Parent Class Constructor 263 | 264 | 265 | // Overriding Constructor 266 | 267 | // With A Constructor, Things Are Bit Tricky/ Different. According To The Specifications , If A Class Extends Another Class And Has No Constructor. Than The Child Class Will Have A Constructor Automatically. -> By Default Its Generated By The JS Engine. 268 | 269 | // Default One 270 | // constructor(...args){ ---> If there is no constructor in the child class, this is created automatically 271 | // // super(...args) 272 | // // } 273 | 274 | // Constructor In Inheriting Classes Mus Call Super (...) And Do It Before Using This. 275 | // We Can Also Use super.method() In Child Class To Call Parent Class Method. 276 | 277 | // class Employee { 278 | // constructor(name) { 279 | // console.log(`${name} - Employee's constructor is here`) 280 | // this.name = name 281 | // } 282 | // login() { 283 | // console.log(`Employee has logged in`); 284 | // } 285 | 286 | // logout() { 287 | // console.log(`Employee has logged out`); 288 | // } 289 | 290 | // requestLeaves(leaves) { 291 | // console.log(`Employee has requested ${leaves} leaves - Auto approved`) 292 | // } 293 | // } 294 | 295 | // class Programmer extends Employee { 296 | // constructor(name) { 297 | // super(name) 298 | // console.log(`This is a newly written constructor`) 299 | // } 300 | // // constructor(...args){ ---> If there is no constructor in the child class, this is created automatically 301 | // // super(...args) 302 | // // } 303 | // requestCoffee(x) { 304 | // console.log(`Employee has requested ${x} coffees`) 305 | // } 306 | // requestLeaves(leaves) { 307 | // super.requestLeaves(4) 308 | // console.log("One extra is granted") 309 | // // console.log(`Employee has requested ${leaves + 1} leaves (One extra)`) 310 | 311 | // } 312 | // } 313 | 314 | // let e = new Programmer("Harry") 315 | // e.login() 316 | // e.requestLeaves(3) 317 | 318 | 319 | // Static Methods 320 | // Static Methods Are Methods Which Are Associated With A Class And Not With Any Instance Of It. 321 | 322 | // Static Method Are Used To Implement Logic Which Does Not Rely On Instance. 323 | 324 | // Static Method Are Used To Implement Function That Belong To A Class As A Whole. And Not To Any Particular Object. 325 | 326 | // We Can Assign Single Static Method; 327 | 328 | // Syntax: 329 | 330 | // class follow { 331 | // static method() { 332 | // console.log("This is a static method") 333 | // } 334 | // } 335 | 336 | // follow.method() 337 | 338 | // Static Methods Aren't Available For Individual Object 339 | 340 | // class Animal { 341 | // constructor(name) { 342 | // this.name = Animal.capitalize(name) 343 | // } 344 | // walk() { 345 | // alert("Animal " + this.name + " is walking") 346 | // } 347 | // static capitalize(name) { 348 | // return name.charAt(0).toUpperCase() + name.substr(1, name.length) 349 | // } 350 | // } 351 | 352 | // j = new Animal("jack") 353 | // j.walk() 354 | // console.log(j.capitalize("thisa")) // --- > this doesnt work 355 | 356 | // Getters And Setters 357 | 358 | // Getters And Setters Are Special Methods Which Are Used To Get And Set The Values Of An Object's Properties. 359 | 360 | // class Person { 361 | // constructor(name) { 362 | // this.name = name 363 | // } 364 | // fly() { 365 | // console.log("I am flying") 366 | // } 367 | // get name() { 368 | // return this._name 369 | // } 370 | // set name(newName) { 371 | // this._name = newName 372 | // } 373 | // } 374 | 375 | // class Animal { 376 | // constructor(name) { 377 | // this._name = name 378 | // } 379 | // fly() { 380 | // console.log("Mai ud rha hu") 381 | // } 382 | // get name() { 383 | // return this._name 384 | // } 385 | 386 | // set name(newName) { 387 | // this._name = newName 388 | // } 389 | 390 | // } 391 | 392 | // class Rabbit extends Animal { 393 | // eatCarrot() { 394 | // console.log("Eating carrot") 395 | // } 396 | // } 397 | 398 | // let a = new Rabbit("Bruno") 399 | // a.fly() 400 | // console.log(a.name) 401 | // a.name = "Jack" 402 | // console.log(a.name) 403 | // let c = 56 404 | 405 | // console.log(a instanceof Animal) 406 | // console.log(a instanceof Rabbit) 407 | // console.log(c instanceof Animal) 408 | 409 | 410 | // InstanceOf Operator 411 | // InstanceOf Operator Is Used To Check If An Object Is An Instance Of A Class. 412 | // Object It Belongs To Certain Class Or Not? 413 | // It Return True If Obj Belongs To The Class Or Any Other Class Inherited From It. 414 | // Syntax: 415 | 416 | // instanceof 417 | 418 | // Practice Set 419 | 420 | // Q1 Create A Class To Create A Complex Number. Create A Constructor To Set The Real And Imaginary Parts. 421 | 422 | // Q2 Write A Method To Add Two Complex Numbers In The Above Class. 423 | 424 | // Q3 Create A Class Student From A Class Human. Override A Method And See Changes. 425 | 426 | // Q4 See If Student Is An Instance Of Human Using InstanceOf Keyword. 427 | 428 | // Q5 Use Getters And Setters To Set And Get The Real And Imaginary Parts Of The Complex Number. 429 | 430 | 431 | // class Complex { 432 | // constructor(real, imaginary) { 433 | // this.real = real 434 | // this.imaginary = imaginary 435 | // } 436 | // add(num) { 437 | // this.real = this.real + num.real 438 | // this.imaginary = this.imaginary + num.imaginary 439 | 440 | // } 441 | 442 | // get real() { 443 | // return this._real 444 | // } 445 | 446 | // get imaginary() { 447 | // return this._imaginary 448 | // } 449 | 450 | // set imaginary(newImaginary) { 451 | // this._imaginary = newImaginary 452 | // } 453 | 454 | // set real(newReal) { 455 | // this._real = newReal 456 | // } 457 | // } 458 | 459 | // let a = new Complex(2, 4) 460 | // console.log(a.real, a.imaginary) 461 | // a.real = 10 462 | // a.imaginary = 10 463 | // let b = new Complex(6, 2) 464 | // a.add(b) 465 | // console.log(`${a.real}+${a.imaginary}i`) 466 | 467 | // class Human { 468 | // constructor(name, favfood) { 469 | // this.name = name 470 | // this.favfood = favfood 471 | // } 472 | // walk() { 473 | // console.log(this.name + "Human is walking") 474 | // } 475 | // } 476 | 477 | // class Student extends Human { 478 | // walk() { 479 | // console.log(this.name + ": Student is walking") 480 | // } 481 | // } 482 | 483 | // let o = new Student("Harry", "Bhindi") 484 | // o.walk() 485 | 486 | // console.log(o instanceof Human) -------------------------------------------------------------------------------- /Ch 12 Advanced JavaScript.js: -------------------------------------------------------------------------------- 1 | // IIFE -> Immediately Invoked Function Expression 2 | 3 | // IIFE Is A JavaScript Function That Runs As Soon As It Is Defined 4 | // (function() { 5 | // console.log("IIFE"); 6 | // })(); 7 | 8 | // // It is used to avoid polluting the global namespace, execute an async-await, etc. 9 | 10 | // let a = () => { 11 | // return new Promise((resolve, reject) => { 12 | // setTimeout(() => { 13 | // resolve(456) 14 | // }, 4000) 15 | // }) 16 | // } 17 | 18 | // (async () => { 19 | // let b = await a() 20 | // console.log(b) 21 | // let c = await a() 22 | // console.log(c) 23 | // let d = await a() 24 | // console.log(d) 25 | // })() 26 | 27 | 28 | // console.log(d) // Throws error 29 | 30 | // Destructuring And Spread Operator 31 | // Destructuring Assignment Is Used To Unpack Values From An Array, Or Properties From An Object, Into Dedicated Variables, In JavaScript. 32 | 33 | // let arr = [3, 5, 8, 9, 12, 14] 34 | // No need to do this: 35 | // let a = arr[0] 36 | // let b = arr[1] 37 | // let [a, b, c, d, ...rest] = arr 38 | // console.log(a, b, c, d, rest) 39 | // let [a, , b, ...rest] = arr 40 | // console.log(a, b, rest) 41 | // let { a, b } = { a: 1, b: 5 } 42 | // console.log(a, b) 43 | 44 | // [10, x,....rest] =[10, 20, 30, 40, 50, 60] 45 | // x will be 20 rest will be [30, 40, 50, 60] 46 | 47 | // Spread Operator 48 | 49 | // Spread Syntax Allow An Iterable such as an array or string to be expanded in places where zero or more arguments (for function calls) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) 50 | // let arr1 = [3, 5, 8] 51 | // let obj1 = { ...arr1 } 52 | // console.log(obj1) 53 | 54 | // function sum(v1, v2, v3) { 55 | // return v1 + v2 + v3 56 | // } 57 | 58 | // console.log(sum(...arr1)) 59 | 60 | // let obj2 = { 61 | // name: "Harry", 62 | // company: "Company xyz", 63 | // address: "XYZ" 64 | // } 65 | 66 | // console.log({ ...obj2, name: "John", company: "ABC" }) 67 | // console.log({ name: "John", company: "ABC", ...obj2 }) // This will print the obj2 object without changing any values 68 | // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment 69 | // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax 70 | 71 | // Local, Global And Function Scope In JavaScript 72 | // var -> Global Scope 73 | // let and const -> Block Scope 74 | // Function Scope -> The variable declared inside a function, becomes local to the function. 75 | 76 | // let p = 9 77 | // function ax() { 78 | // let a = 8; 79 | // console.log(p) 80 | // console.log(a) 81 | // } 82 | 83 | // ax() 84 | // console.log(p) 85 | // console.log(a) 86 | 87 | 88 | // Hoisting In JavaScript 89 | // Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution 90 | 91 | // let a; 92 | // Following two lines will run successfully due to JavaScript hoisting 93 | // console.log(a) 94 | // greet() 95 | // var greet = function() { 96 | // console.log("Good morning") 97 | // } 98 | 99 | // var a = 9; // Declaration hoisted to the top but initialization is not 100 | // console.log(a) 101 | 102 | // Hoisting With Let And Var 103 | // let and const are not hoisted 104 | // console.log(num); 105 | // let num = 6; -> Throws an error 106 | // var num = 6; -> Doesn't throw an error 107 | // const num = 6; -> Throws an error 108 | 109 | // Function Expression And Class Expression Are Not Hoisted 110 | // Function Expression Me = Sign Ata He 111 | 112 | // Closer Set 113 | 114 | // A Closer Is A Function With Lexical Environment 115 | 116 | // function init() { 117 | // var name = 'Mozilla'; // name is a local variable created by init 118 | // function displayName() { 119 | // // displayName() is the inner function, a closure 120 | // console.log(name); // use variable declared in the parent function 121 | // } 122 | // name = "Harry" 123 | // return displayName; 124 | // } 125 | // let c = init(); 126 | // c() 127 | 128 | 129 | // function returnFunc() { 130 | // const x = () => { 131 | // let a = 1 132 | // console.log(a) 133 | // const y = () => { 134 | // // let a = 2 135 | // console.log(a) 136 | // const z = () => { 137 | // // let a = 3 138 | // console.log(a) 139 | // } 140 | // z() 141 | // } 142 | // a = 999 143 | // y() 144 | // } 145 | // return x 146 | // } 147 | 148 | // let a = returnFunc() 149 | // a() 150 | 151 | // Closure -> Function + Its Lexical Environment 152 | // Reference Milta He 153 | 154 | // Lexical Environment -> The Environment Of The Function -> Mere Pass Nahi He To Mere Pass Ka Environment Me Ase Check Karega 155 | 156 | // Arrow Function 157 | 158 | // const sayHello = name => { 159 | // console.log("greeting" + " " + name) 160 | // console.log("hi") 161 | // } 162 | 163 | // const x = { 164 | // name: "Harry", 165 | // role: "Js Developer", 166 | // exp: 30, 167 | // show: function() { 168 | // // let that = this 169 | // // console.log(this) 170 | // setTimeout(() => { 171 | // // console.log(`The name is ${that.name}\nThe role is ${that.role}`) 172 | // console.log(`The name is ${this.name}\nThe role is ${this.role}`) 173 | // }, 2000) 174 | // } 175 | // } 176 | // sayHello("Harry", "Good Afternoon") 177 | // console.log(x.name, x.exp) 178 | // x.show() 179 | 180 | // Arrow Function Uses Lexical This 181 | 182 | // Practice Set 183 | 184 | // const a = async (text, n = 2) => { 185 | // return new Promise((resolve, reject) => { 186 | // setTimeout(() => { 187 | // resolve(text) 188 | // }, 1000 * n) 189 | // }) 190 | // } 191 | 192 | // ( 193 | // async () => { 194 | // let text = await a("Hello") 195 | // console.log(text) 196 | // text = await a("World") 197 | // console.log(text) 198 | // } 199 | // )() 200 | 201 | // function sum(a, b, c) { 202 | // return a + b + c 203 | // } 204 | 205 | // let x = [1, 3, 5] 206 | // console.log(sum(...x)); 207 | 208 | // (async () => { 209 | // let text = await a("I am resolving after 1 second", 1) 210 | // console.log(text) 211 | // text = await a("I am resolving after 4 seconds", 4) 212 | // console.log(text) 213 | // } 214 | // )() 215 | 216 | // function simpleInterest(p, r, t) { 217 | // return (p * r * t) / 100; 218 | // } 219 | 220 | // console.log(simpleInterest(100, 5, 1)) 221 | 222 | // Regex Expression Or Regular Expression 223 | // https://regexr.com/ 224 | // const regex = /(Harry){2}/gi 225 | // const text = "Harryharry is a very very nice awesome nice very boy" 226 | // console.log(text.replace(regex, "VERY")) 227 | 228 | // Event Loop 229 | 230 | // Asynchronous CallBack 231 | // Sometimes the JavaScript code can take a lot of time and this can block the 232 | // page re render 233 | // JavaScript has asynchronous callbacks for non blocking behavior 234 | // JavaScript runtime can do only one thing at a time 235 | // Browser gives us other things which work along with the runtime like Web 236 | // APIs. 237 | // In node.js these are available as C++ APIs 238 | 239 | // setTimeout(function timer() { 240 | // console.log('You clicked the button!'); 241 | // }, 2000); 242 | 243 | // console.log("Hi!"); 244 | 245 | // setTimeout(function timeout() { 246 | // console.log("Click the button!"); 247 | // }, 5000); 248 | 249 | // console.log("Welcome to loupe."); 250 | 251 | // Task Queue 252 | // JavaScript can do only one thing at a time 253 | // The rest are queued to the task queue waiting to be executed 254 | // When we run setTimeout, webapis will run a timer and push the function 255 | // provided to setTimeout to the task queue once the timer evis 256 | // These tasks will be pushed to the stack where they can executed 257 | 258 | // Event Loop 259 | 260 | // JavaScript has a runtime model based on an event loop, which is responsible 261 | // for executing the code, collecting and processing events, and executing queued 262 | // sub-tasks 263 | // The event loop pushes the tasks from the task queue to the call stack 264 | // setTimeout(func1, 0) can be used to defer a function until all the pending tasks 265 | // (so far) have been executed 266 | // We can see how these things work in action by visiting 267 | // For Understanding Call Stack In Js :http://latentflip.com/loupe/ 268 | 269 | // Module In JS 270 | 271 | 272 | // const hello = ()=>{ 273 | // console.log("Hello Harry") 274 | // } 275 | 276 | // const ahello = (name)=>{ 277 | // console.log("Hello " + name) 278 | // } 279 | 280 | // module.exports = {hello, ahello};// same as below line 281 | // // module.exports = {hello: hello, ahello: ahello}; 282 | 283 | // // ES6 Modules 284 | // export const hello = ()=>{ 285 | // console.log("Hello Harry") 286 | // } 287 | 288 | // export const ahello = (name)=>{ 289 | // console.log("Hello " + name) 290 | // } 291 | 292 | // const harry = ()=>{ 293 | // console.log("Hello " + "Harry") 294 | // } 295 | 296 | // export default harry; 297 | -------------------------------------------------------------------------------- /Ch 2 Expression & Conditional Statement Practice Set.js: -------------------------------------------------------------------------------- 1 | // Ch 2 Expression & Conditional Statement Practice Set 2 | 3 | 4 | // Q1) Use Logical Operator To Find Whether The Age Of a Person Lies Between 10 & 20. 5 | 6 | let age = 15; 7 | 8 | if (age >= 10 && age <= 20) { 9 | console.log("The age is between 10 and 20."); 10 | } else { 11 | console.log("The age is not between 10 and 20."); 12 | } 13 | 14 | 15 | // Q2) Demonstrate The Use Of Switch Statement In JS With an Example. 16 | 17 | let day = 3; 18 | let dayName; 19 | 20 | switch (day) { 21 | case 1: 22 | dayName = "Monday"; 23 | break; 24 | case 2: 25 | dayName = "Tuesday"; 26 | break; 27 | case 3: 28 | dayName = "Wednesday"; 29 | break; 30 | case 4: 31 | dayName = "Thursday"; 32 | break; 33 | case 5: 34 | dayName = "Friday"; 35 | break; 36 | case 6: 37 | dayName = "Saturday"; 38 | break; 39 | case 7: 40 | dayName = "Sunday"; 41 | break; 42 | default: 43 | dayName = "Invalid day"; 44 | } 45 | 46 | console.log(dayName); 47 | 48 | 49 | // Q3) Write JS Program To Find Whether the Number Is Divisible By 2 And 3. 50 | 51 | let number = 12; 52 | 53 | if (number % 2 === 0 && number % 3 === 0) { 54 | console.log(number + " is divisible by both 2 and 3."); 55 | } else { 56 | console.log(number + " is not divisible by both 2 and 3."); 57 | } 58 | 59 | 60 | // Q4) Print "You Can Drive" Or "You Can't Drive" Based On Age Being Greater Than 18 Using Ternary Operator 61 | 62 | let age = 20; 63 | let canDrive = age > 18 ? "You can drive." : "You can't drive."; 64 | 65 | console.log(canDrive); 66 | 67 | 68 | -------------------------------------------------------------------------------- /Ch 2 Expression & Conditional Statement.js: -------------------------------------------------------------------------------- 1 | // Arithmetic Operators 2 | // + Addition 3 | // - Subtraction 4 | // * Multiplication 5 | // ** Exponential 6 | // / Division 7 | // % Modulus 8 | // ++ Increment 9 | // -- Decrement 10 | 11 | // -> Example 12 | // Arithmetic Operators 13 | 14 | let addition = 5 + 2; // 7 15 | let subtraction = 8 - 3; // 5 16 | let multiplication = 4 * 3; // 12 17 | let exponentiation = 2 ** 4; // 16 18 | let division = 10 / 2; // 5 19 | let modulus = 9 % 2; // 1 20 | let increment = 5; 21 | increment++; // 6 22 | let decrement = 10; 23 | decrement--; // 9 24 | 25 | 26 | // Assignment Operators 27 | // = X = Y 28 | // += X = X + Y 29 | // -= X = X - Y 30 | // *= X = X * Y 31 | // /= X = X / Y 32 | // %= X = X % Y 33 | // **= X = X ** Y 34 | 35 | // -> Example 36 | // Assignment Operators 37 | let x = 5; 38 | x += 3; // equivalent to x = x + 3 39 | x -= 2; // equivalent to x = x - 2 40 | x *= 4; // equivalent to x = x * 4 41 | x /= 2; // equivalent to x = x / 2 42 | x %= 3; // equivalent to x = x % 3 43 | x **= 2; // equivalent to x = x ** 2 44 | 45 | 46 | // Comparison Operators 47 | // == Equal To 48 | // != Not Equal To 49 | // === Equal Value And Type 50 | // !== Not Equal Value Or Type 51 | // > Greater Than 52 | // < Less Than 53 | // >= Greater Than Or Equal To 54 | // <= Less Than Or Equal To 55 | // ? Ternary Operator 56 | 57 | // -> Example 58 | // Comparison Operators 59 | let isEqual = (5 == 5); // true 60 | let isNotEqual = (5 != 3); // true 61 | let isEqualValueAndType = (5 === '5'); // false 62 | let isNotEqualValueOrType = (5 !== '5'); // true 63 | let isGreaterThan = (10 > 5); // true 64 | let isLessThan = (3 < 7); // true 65 | let isGreaterThanOrEqual = (8 >= 8); // true 66 | let isLessThanOrEqual = (4 <= 2); // false 67 | 68 | 69 | // Logical Operators 70 | // && Logical And 71 | // || Logical Or 72 | // ! Logical Not 73 | 74 | // -> Example 75 | // Logical Operators 76 | let logicalAnd = (true && false); // false 77 | let logicalOr = (true || false); // true 78 | let logicalNot = !true; // false 79 | 80 | 81 | 82 | // Bitwise Operators 83 | // Bitwise AND (&): Performs a bitwise AND operation on each pair of corresponding bits. The result is 1 if both bits are 1; otherwise, it is 0. 84 | 85 | // Bitwise OR (|): Performs a bitwise OR operation on each pair of corresponding bits. The result is 1 if at least one of the bits is 1; otherwise, it is 0. 86 | 87 | // Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation on each pair of corresponding bits. The result is 1 if the bits are different; otherwise, it is 0. 88 | 89 | // Bitwise NOT (~): Flips the bits of a number. It converts each 0 to 1 and each 1 to 0. 90 | 91 | // Left Shift (<<): Shifts the bits of a number to the left by a specified number of positions. This operation effectively multiplies the number by 2 to the power of the specified shift amount. 92 | 93 | // Right Shift (>>): Shifts the bits of a number to the right by a specified number of positions. This operation effectively divides the number by 2 to the power of the specified shift amount. 94 | 95 | // Zero-fill Right Shift (>>>): Similar to the right shift operator (>>), but it always fills in the shifted positions with zeros. This is known as the zero-fill right shift. 96 | 97 | // Bitwise operators are commonly used in JavaScript for low-level manipulation of binary data, creating flags, and optimizing certain calculations. However, they are not frequently used in general-purpose programming and should be used judiciously due to their complexity and potential for confusion. 98 | 99 | // It's important to note that JavaScript treats numeric values as 32-bit signed integers when performing bitwise operations. To perform bitwise operations on larger numbers, consider using additional techniques or external libraries. 100 | 101 | // I hope these notes help you understand the basics of bitwise operators in JavaScript! 102 | 103 | // -> Example 104 | // Bitwise Operators 105 | let bitwiseAND = 5 & 3; // 1 106 | let bitwiseOR = 5 | 3; // 7 107 | let bitwiseXOR = 5 ^ 3; // 6 108 | let bitwiseNOT = ~5; // -6 109 | let leftShift = 5 << 2; // 20 110 | let rightShift = 5 >> 1; // 2 111 | let zeroFillRightShift = 5 >>> 1; // 2 112 | 113 | 114 | // Comments 115 | 116 | // Single Line Comment 117 | 118 | /* Multi Line Comment */ 119 | 120 | 121 | // Conditional Statement 122 | // 3 Types Of Conditional Statement Are Available 123 | // If Statement 124 | // If....Else Statement 125 | // If....Else If....Else Statement 126 | 127 | // If Statement 128 | 129 | // if(condition){ 130 | // //Execute This Code 131 | // } -> Execute Till Condition True 132 | 133 | // -> Example 134 | let x = 10; 135 | 136 | if (x > 5) { 137 | console.log("x is greater than 5"); // This block will be executed since the condition is true 138 | } 139 | 140 | 141 | 142 | // If....Else Statement 143 | 144 | // if(condition){ 145 | // //Execute This Code If Condition Is True 146 | // } 147 | // else { 148 | // //Execute This Code If Condition Is False 149 | // } 150 | 151 | // -> Example 152 | 153 | let age = 18; 154 | 155 | if (age >= 18) { 156 | console.log("You are eligible to vote."); // This block will be executed since the condition is true 157 | } else { 158 | console.log("You are not eligible to vote."); // This block will be executed if the condition is false 159 | } 160 | 161 | 162 | 163 | // If....Else If Statement 164 | // -> Sometime We Required To Check Condition Again And Again. 165 | 166 | // if (condition1) { 167 | // // Code To Be Executed If Condition1 Is True 168 | // } else if (condition2) { 169 | // // Code To Be Executed If Condition2 Is True 170 | // } else { 171 | // // Code To Be Executed If All Conditions Are False 172 | // } 173 | 174 | // -> Example 175 | 176 | let num = 5; 177 | 178 | if (num > 0) { 179 | console.log("Number is positive."); 180 | } else if (num < 0) { 181 | console.log("Number is negative."); 182 | } else { 183 | console.log("Number is zero."); 184 | } 185 | 186 | 187 | // JavaScript Ternary Operator 188 | 189 | // The ternary operator, also known as the conditional operator, provides a concise way to write conditional expressions in JavaScript. 190 | 191 | // It is represented by the syntax: condition ? expression1 : expression2. -> True : False 192 | 193 | // The condition is evaluated first, and if it is true, expression1 is executed. If the condition is false, expression2 is executed. 194 | 195 | // -> Usage and Benefits: 196 | 197 | // The ternary operator is often used as a shorthand alternative to if...else statements when there are simple conditions and expressions involved. 198 | 199 | // It makes the code more concise and readable, especially for shorter conditional statements. 200 | 201 | // It can be used to assign a value to a variable based on a condition without the need for a separate if statement. 202 | 203 | // Examples: 204 | 205 | // Assigning a value based on a condition: 206 | 207 | 208 | let dp = 18; 209 | let message = (dp >= 18) ? "You are an adult" : "You are not an adult"; 210 | 211 | 212 | 213 | // Returning a value from a function based on a condition: 214 | 215 | function checkEvenOrOdd(num) { 216 | return (num % 2 === 0) ? "Even" : "Odd"; 217 | } 218 | 219 | 220 | // Nesting ternary operators (though it's recommended to keep it simple for readability): 221 | 222 | let nums = 10; 223 | let result = (nums > 0) ? "Positive" : (nums < 0) ? "Negative" : "Zero"; 224 | 225 | 226 | // While the ternary operator can make code more concise, it should be used judiciously to maintain code readability. Complex conditions or expressions may be better suited for if...else statements. 227 | 228 | // Avoid nesting too many ternary operators, as it can make the code harder to understand and maintain. 229 | 230 | // Use appropriate spacing and formatting to enhance the readability of ternary expressions. 231 | 232 | // Remember, a ternary operator is a powerful tool for writing conditional expressions in a concise manner. However, it's important to strike a balance between readability and simplicity when using it in your JavaScript code. 233 | 234 | 235 | // Prefix Increment: 236 | 237 | let x = 5; 238 | let result = ++x; // Increment x by 1 and assign the new value to result 239 | console.log(result); // Output: 6 240 | console.log(x); // Output: 6 241 | 242 | // Postfix Increment: 243 | 244 | let y = 5; 245 | let result = y++; // Assign the current value of y to result, then increment y by 1 246 | console.log(result); // Output: 5 247 | console.log(y); // Output: 6 248 | -------------------------------------------------------------------------------- /Ch 3 Loops And Functions Practice Set.js: -------------------------------------------------------------------------------- 1 | // Q1) Write A Program To Print Marks Of Student In An Object Using For Loop 2 | const marks = { 3 | dp: 100, 4 | ap: 99, 5 | hp: 98 6 | }; 7 | 8 | for (let student in marks) { 9 | console.log(`${student}: ${marks[student]}`); 10 | } 11 | 12 | // Output 13 | // dp: 100 14 | // ap: 99 15 | // hp: 98 16 | 17 | // Q2) Write A Program In Q1 Using Using For In Loop 18 | const marks = { 19 | dp: 100, 20 | ap: 99, 21 | hp: 98 22 | }; 23 | 24 | for (let student in marks) { 25 | console.log(`${student}: ${marks[student]}`); 26 | } 27 | 28 | // Output 29 | // dp: 100 30 | // ap: 99 31 | // hp: 98 32 | 33 | 34 | // Q3) Write A Program To Print "Try Again" Until The User Enter The Correct Number 35 | 36 | let correctNumber = 7; 37 | let userNumber; 38 | 39 | do { 40 | userNumber = parseInt(prompt('Enter a number:')); 41 | if (userNumber !== correctNumber) { 42 | console.log('Try again'); 43 | } 44 | } while (userNumber !== correctNumber); 45 | 46 | // This program will keep prompting the user to enter a number until they enter the correct number (in this case, 7). 47 | 48 | // Q4) Write A Function To Find the Mean Of 5 Numbers 49 | 50 | function findMean(num1, num2, num3, num4, num5) { 51 | const sum = num1 + num2 + num3 + num4 + num5; 52 | const mean = sum / 5; 53 | return mean; 54 | } 55 | 56 | const result = findMean(10, 20, 30, 40, 50); 57 | console.log('Mean:', result); 58 | 59 | // Output 60 | 61 | // Mean: 30 62 | 63 | // Q5)Write a function named multiplyByTwo that takes a number as an argument and returns the result of multiplying that number by 2. 64 | 65 | function multiplyByTwo(num) { 66 | return num * 2; 67 | } 68 | 69 | // Q6)Write a function named reverseString that takes a string as an argument and returns the reverse of that string. 70 | 71 | function reverseString(str) { 72 | return str.split('').reverse().join(''); 73 | } 74 | 75 | // Q7)Write a function named printEvenNumbers that takes a number as an argument and prints all the even numbers from 0 to that number. 76 | 77 | function printEvenNumbers(num) { 78 | for (let i = 0; i <= num; i++) { 79 | if (i % 2 === 0) { 80 | console.log(i); 81 | } 82 | } 83 | } 84 | 85 | // Q8) Write a function named calculateFactorial that takes a number as an argument and returns the factorial of that number. 86 | 87 | function calculateFactorial(num) { 88 | if (num === 0 || num === 1) { 89 | return 1; 90 | } 91 | 92 | let factorial = 1; 93 | for (let i = 2; i <= num; i++) { 94 | factorial *= i; 95 | } 96 | 97 | return factorial; 98 | } 99 | 100 | // Q9) Write a function named countOccurrences that takes an array of numbers and a target number as arguments and returns the number of times the target number appears in the array. 101 | 102 | function countOccurrences(arr, target) { 103 | let count = 0; 104 | for (let num of arr) { 105 | if (num === target) { 106 | count++; 107 | } 108 | } 109 | return count; 110 | } 111 | 112 | // Q10) What is an arrow function in JavaScript? 113 | 114 | // An arrow function is a shorter syntax for writing function expressions. It uses the => arrow token and does not bind its own this value. It is often used for writing concise and inline functions. -------------------------------------------------------------------------------- /Ch 3 Loops And Functions.js: -------------------------------------------------------------------------------- 1 | // Loops & Functions 2 | // Loops and functions are essential concepts in JavaScript programming that help to create efficient and reusable code. 3 | 4 | 5 | // Types Of Loops 6 | //For Loop -> Loop a Block Of Code No Of Time 7 | //For In Loop -> Loop Through The Key Of An Object 8 | //For Of Loop -> Loop Through The Value Of An Object 9 | //While Loop -> Loop Of Block Based On Specific Condition 10 | // Do...While Loop -> While Loop Variant Which Run a At Least Once 11 | 12 | 13 | // For Loop 14 | // Syntax 15 | // for(Statement1;Statement2;Statement3){ 16 | // // Code To Be Executed 17 | // } 18 | // Statement1 -> Executed One Time 19 | // Statement2 -> Condition Based -> Based On This Loop Body Will Be Executed 20 | // Statement3 -> Executed Every Time The Loop Body Is Executed 21 | 22 | 23 | // Example 24 | for (let i = 0; i < 5; i++) { 25 | console.log(i); // prints numbers from 0 to 4 26 | } 27 | 28 | 29 | // For In Loop 30 | //Loop Through The Key Of An Object 31 | // For In Loop Works With Array Also 32 | 33 | // Example 34 | const person = { 35 | name: 'John', 36 | age: 30, 37 | occupation: 'Developer' 38 | // key:'value' 39 | }; 40 | 41 | for (let key in person) { //(let a in person) -> console.log(a); 42 | console.log(key); // prints "name", "age", "occupation" 43 | console.log(person[key]); // prints the corresponding values "John", 30, "Developer" 44 | } 45 | 46 | 47 | // For Of Loop 48 | // Loop Through The Value Of An Object 49 | // Object Must Be Iterable 50 | 51 | // Example 52 | const fruits = ['apple', 'banana', 'orange']; 53 | 54 | for (let fruit of fruits) { 55 | console.log(fruit); // prints "apple", "banana", "orange" 56 | } 57 | 58 | const message = 'Hello'; 59 | 60 | for (let char of message) { 61 | console.log(char); // prints "H", "e", "l", "l", "o" 62 | } 63 | 64 | 65 | // While Loop 66 | // If Condition Never False -> Loop Will Never End -> Crush JS Run Time 67 | // Also Called In Infinite Loop -> Don't Try This Circus 68 | 69 | // Syntax 70 | // while(condition){ 71 | // // Code To Be Executed 72 | // } 73 | 74 | // Example 75 | let i = 0; 76 | while (i < 5) { 77 | console.log(i); // prints numbers from 0 to 4 78 | i++; 79 | } 80 | 81 | 82 | // ALT + SHIFT + DOWN ARROW KEY -> Replicate Selected Code 83 | 84 | 85 | // Do.....While Loop 86 | // Do...While Loop -> While Loop Variant Which Run a At Least Once 87 | // Syntax 88 | 89 | // do { 90 | // // Code To Be Executed 91 | // } while(Condition) 92 | 93 | // Example 94 | let i = 0; 95 | do { 96 | console.log(i); // prints numbers from 0 to 4 -> Executed At Least Once 97 | i++; 98 | } while (i < 5); 99 | 100 | let i = 6; 101 | do { 102 | console.log(i); // prints numbers from 0 to 4 -> Executed At Least Once 103 | i++; 104 | } while (i < 5); 105 | 106 | // Output -> 6 107 | 108 | 109 | // Functions 110 | // Functions are reusable blocks of code that perform a specific task. They help in organizing code, improving reusability, and reducing redundancy. A function can accept parameters (inputs) and return a value. 111 | 112 | // function myfun(parameter1, parameter2){ 113 | // //Code -> Parameter Behave As Local Variables 114 | // } 115 | 116 | // myfun(6,7); -> Function Invocation 117 | // A. Function declaration: 118 | // B function declaration defines a named function that can be called later in the code. 119 | 120 | // Example 121 | function greet(name) { 122 | console.log(`Hello, ${name}!`); 123 | } 124 | 125 | greet("John"); // prints "Hello, John!" 126 | greet("Sarah"); // prints "Hello, Sarah!" 127 | 128 | // Function expression: 129 | // A function expression assigns a function to a variable. It can be anonymous or named. 130 | 131 | const greet = function (name) { 132 | console.log(`Hello, ${name}!`); 133 | }; 134 | 135 | greet("John"); // prints "Hello, John!" 136 | greet("Sarah"); // prints "Hello, Sarah!" 137 | 138 | // Arrow function: 139 | // Arrow functions provide a concise syntax for writing functions. They are anonymous and lexically bind the this value. 140 | 141 | const greet = (name) => { 142 | console.log(`Hello, ${name}!`); 143 | }; 144 | 145 | greet("John"); // prints "Hello, John!" 146 | greet("Sarah"); // prints "Hello, Sarah!" 147 | 148 | // Returning a value: 149 | // Functions can return a value using the return statement. The returned value can be stored in a variable or used directly. 150 | 151 | function add(a, b) { 152 | return a + b; 153 | } 154 | 155 | const result = add(3, 4); 156 | console.log(result); // prints 7 157 | 158 | // Default parameters: 159 | // Default parameters allow you to assign default values to function parameters if no argument is passed. 160 | 161 | 162 | function multiply(a, b = 1) { 163 | return a * b; 164 | } 165 | 166 | console.log(multiply(5)); // prints 5 167 | console.log(multiply(5, 2)); // prints 10 168 | -------------------------------------------------------------------------------- /Ch 4 String Practice Set.js: -------------------------------------------------------------------------------- 1 | // Ch 4 String Practice Set 2 | 3 | // Q1)Write a program that counts the number of characters in a given string. 4 | 5 | 6 | 7 | // const str = "Hello, World!"; 8 | // const count = str.length; 9 | // console.log(count); // Output: 13 10 | 11 | 12 | // Q2)Write a program that checks if a string contains a specific substring. 13 | 14 | 15 | 16 | // const str = "Hello, World!"; 17 | // const substring = "World"; 18 | // const containsSubstring = str.includes(substring); 19 | // console.log(containsSubstring); // Output: true 20 | 21 | 22 | 23 | // Q3)Write a program that converts a string to uppercase. 24 | 25 | 26 | 27 | // const str = "Hello, World!"; 28 | // const uppercaseStr = str.toUpperCase(); 29 | // console.log(uppercaseStr); // Output: HELLO, WORLD! 30 | 31 | 32 | 33 | // Q4)Write a program that extracts a portion of a string based on start and end indexes. 34 | 35 | 36 | 37 | // const str = "Hello, World!"; 38 | // const extractedStr = str.slice(7, 12); 39 | // console.log(extractedStr); // Output: World 40 | 41 | 42 | // Q5)Write a program that replaces a specific substring with another substring. 43 | 44 | 45 | 46 | // const str = "Hello, John!"; 47 | // const newStr = str.replace("John", "Alice"); 48 | // console.log(newStr); // Output: Hello, Alice! 49 | 50 | 51 | 52 | // Q6)Write a program that splits a string into an array of substrings based on a delimiter. 53 | 54 | 55 | 56 | // const str = "Hello, World!"; 57 | // const arr = str.split(","); 58 | // console.log(arr); // Output: ["Hello", " World!"] 59 | 60 | // Q7)Write a program that checks if a string starts with a specific character or substring. 61 | 62 | 63 | 64 | // const str = "Hello, World!"; 65 | // const startsWithHello = str.startsWith("Hello"); 66 | // console.log(startsWithHello); // Output: true 67 | 68 | 69 | // Q8)Write a program that checks if a string ends with a specific character or substring. 70 | 71 | 72 | 73 | // const str = "Hello, World!"; 74 | // const endsWithWorld = str.endsWith("World!"); 75 | // console.log(endsWithWorld); // Output: true 76 | 77 | 78 | // Q9)Write a program that trims whitespace from the beginning and end of a string. 79 | 80 | 81 | 82 | // const str = " Hello, World! "; 83 | // const trimmedStr = str.trim(); 84 | // console.log(trimmedStr); // Output: Hello, World! 85 | 86 | 87 | // Q10)Write a program that checks if a string is empty. 88 | 89 | 90 | 91 | // const str = ""; 92 | // const isEmpty = str.length === 0; 93 | // console.log(isEmpty); // Output: true -------------------------------------------------------------------------------- /Ch 4 String.js: -------------------------------------------------------------------------------- 1 | // Strings 2 | 3 | // A string is a sequence of characters enclosed in single quotes (') or double quotes ("). Strings are immutable, meaning that once created, they cannot be changed. However, string methods can be used to manipulate and extract information from strings. 4 | 5 | // Strings are used to store and manipulate text 6 | 7 | // String -> Collection of characters 8 | 9 | // Single Quotes -> let name = 'dp'; 10 | // Double Quotes -> let name = "dp"; 11 | 12 | let name = "dp"; 13 | // console.log(name[3]); -> undefined 14 | 15 | // Template Literals 16 | 17 | // After ES6, Template Literals came into use, utilizing backticks (`). 18 | 19 | let boy1 = "hmm"; 20 | let boy2 = 'ok'; 21 | 22 | // Print "hmm nice ok" 23 | // let sentence = `boy1 "nice" 'is' boy2` -> We make a string using single or double quotes, both usage possible if string is made through backticks 24 | 25 | // String Interpolation 26 | let sentence = `${boy1} nice ${boy2}`; 27 | console.log(sentence); // Output: hmm nice ok 28 | 29 | let fruit = `Bana\'na`; // Bana'na 30 | console.log(fruit); 31 | 32 | // \' -> Escape character -> Count as one character 33 | // \n -> New line 34 | // \t -> Tab 35 | // \r -> Carriage return 36 | 37 | // String Methods & Properties 38 | 39 | // Accessing Characters: 40 | // Individual characters in a string can be accessed using square brackets and their index. Remember, indexing starts at 0. 41 | 42 | const message = 'Hello'; 43 | console.log(message[0]); // Output: H 44 | console.log(message[3]); // Output: l 45 | 46 | // String Concatenation: 47 | // Strings can be concatenated using the + operator or the concat() method. 48 | 49 | const firstName = 'John'; 50 | const lastName = 'Doe'; 51 | const fullName = firstName + ' ' + lastName; 52 | console.log(fullName); // Output: John Doe 53 | 54 | // Using concat() 55 | const greetingMessage = 'Hello, '; 56 | const nameConcat = 'John'; 57 | const greeting = greetingMessage.concat(nameConcat); 58 | console.log(greeting); // Output: Hello, John 59 | 60 | // Finding Substrings: 61 | // The indexOf() method returns the index of the first occurrence of a substring within a string. It returns -1 if the substring is not found. 62 | 63 | const welcomeMessage = 'Hello, world!'; 64 | console.log(welcomeMessage.indexOf('world')); // Output: 7 65 | console.log(welcomeMessage.indexOf('open')); // Output: -1 66 | 67 | // Extracting Substrings: 68 | // The slice() method extracts a portion of a string based on the start and end indexes. 69 | 70 | console.log(welcomeMessage.slice(0, 5)); // Output: Hello 71 | console.log(welcomeMessage.slice(7)); // Output: world! 72 | 73 | // Replacing Substrings: 74 | // The replace() method replaces a specified substring with another substring. 75 | 76 | const personalizedMessage = 'Hello, John!'; 77 | console.log(personalizedMessage.replace('John', 'Alice')); // Output: Hello, Alice! 78 | 79 | // Splitting Strings: 80 | // The split() method splits a string into an array of substrings based on a specified delimiter. 81 | 82 | console.log(welcomeMessage.split(' ')); // Output: ["Hello,", "world!"] 83 | 84 | // Checking if a String Contains a Substring: 85 | // The includes() method checks if a string contains a specified substring and returns true or false. 86 | 87 | console.log(welcomeMessage.includes('World')); // Output: true 88 | console.log(welcomeMessage.includes('open')); // Output: false 89 | 90 | // String Length: 91 | // The length property returns the number of characters in a string. 92 | 93 | console.log(welcomeMessage.length); // Output: 13 94 | 95 | // String Slice: 96 | // The slice() method extracts a portion of a string based on the start and end indexes. It returns a new string. 97 | 98 | console.log(welcomeMessage.slice(7)); // Output: world! 99 | console.log(welcomeMessage.slice(0, 5)); // Output: Hello 100 | 101 | // String Substring: 102 | // The substring() method is similar to slice(), but it doesn't accept negative indexes. It returns a new string. 103 | 104 | console.log(welcomeMessage.substring(7)); // Output: world! 105 | console.log(welcomeMessage.substring(0, 5)); // Output: Hello 106 | 107 | // String Substr: 108 | // The substr() method extracts a portion of a string based on the start index and length. It returns a new string. 109 | 110 | console.log(welcomeMessage.substr(7)); // Output: world! 111 | console.log(welcomeMessage.substr(0, 5)); // Output: Hello 112 | 113 | // String Replace: 114 | // The replace() method replaces a specified substring with another substring. It returns a new string. 115 | 116 | console.log(personalizedMessage.replace('John', 'Alice')); // Output: Hello, Alice! 117 | 118 | // String ReplaceAll: 119 | // The replaceAll() method replaces all occurrences of a specified substring with another substring. It returns a new string. (Available from ECMAScript 2021) 120 | 121 | const repetitiveMessage = 'Hello, John! John is a good guy.'; 122 | console.log(repetitiveMessage.replaceAll('John', 'Alice')); // Output: Hello, Alice! Alice is a good guy. 123 | 124 | // String toUpperCase and toLowerCase: 125 | // The toUpperCase() and toLowerCase() methods convert a string to uppercase and lowercase, respectively. They return a new string. 126 | 127 | console.log(welcomeMessage.toUpperCase()); // Output: HELLO, WORLD! 128 | console.log(welcomeMessage.toLowerCase()); // Output: hello, world! 129 | 130 | // String Concatenation: 131 | // The concat() method concatenates two or more strings and returns a new string. 132 | 133 | console.log(firstName.concat(' ', lastName)); // Output: John Doe 134 | 135 | // String Trim: 136 | // The trim() method removes whitespace from both ends of a string and returns a new string. 137 | 138 | const messageWithWhitespace = ' Hello, world! '; 139 | console.log(messageWithWhitespace.trim()); // Output: Hello, world! 140 | 141 | // String TrimStart and TrimEnd: 142 | // The trimStart() and trimEnd() methods remove whitespace from the beginning and end of a string, respectively. They return a new string. (Available from ECMAScript 2021) 143 | 144 | console.log(messageWithWhitespace.trimStart()); // Output: Hello, world! 145 | console.log(messageWithWhitespace.trimEnd()); // Output: Hello, world! 146 | 147 | // String PadStart and PadEnd: 148 | // The padStart() and padEnd() methods pad a string with a specified character to a given length. They return a new string. (Available from ECMAScript 2017) 149 | 150 | const paddedMessage = 'Hello'; 151 | console.log(paddedMessage.padStart(10, '*')); // Output: *****Hello 152 | console.log(paddedMessage.padEnd(10, '-')); // Output: Hello----- 153 | 154 | // String CharAt and CharCodeAt: 155 | // The charAt() method returns the character at a specified index in a string. 156 | // The charCodeAt() method returns the Unicode value of the character at a specified index in a string. 157 | 158 | console.log(message.charAt(0)); // Output: H 159 | console.log(message.charCodeAt(0)); // Output: 72 160 | 161 | // String Split: 162 | // The split() method splits a string into an array of substrings based on a specified delimiter. 163 | 164 | console.log(welcomeMessage.split(',')); // Output: ["Hello", " World!"] 165 | 166 | // Method summary: 167 | // String length 168 | // String slice() 169 | // String substring() 170 | // String substr() 171 | // String replace() 172 | // String replaceAll() 173 | // String toUpperCase() 174 | // String toLowerCase() 175 | // String concat() 176 | // String trim() 177 | // String trimStart() 178 | // String trimEnd() 179 | // String padStart() 180 | // String padEnd() 181 | // String charAt() 182 | // String charCodeAt() 183 | // String split() -------------------------------------------------------------------------------- /Ch 5 Array Practice Set.js: -------------------------------------------------------------------------------- 1 | // Ch 5 Array Practice Set 2 | 3 | 4 | 5 | // Q1)How do you create an empty array in JavaScript? 6 | 7 | // Answer: 8 | 9 | // const emptyArray = []; 10 | 11 | 12 | // Q2)How do you check if an array is empty in JavaScript? 13 | 14 | // Answer: 15 | 16 | // const array = []; 17 | 18 | // if (array.length === 0) { 19 | // console.log("The array is empty"); 20 | // } else { 21 | // console.log("The array is not empty"); 22 | // } 23 | 24 | 25 | // Q3)How do you add elements to the end of an array in JavaScript? 26 | 27 | // Answer: 28 | 29 | // const array = [1, 2, 3]; 30 | // array.push(4, 5); 31 | // console.log(array); // Output: [1, 2, 3, 4, 5] 32 | 33 | 34 | // Q4)How do you access an element at a specific index in an array? 35 | 36 | // Answer: 37 | 38 | // const array = [1, 2, 3]; 39 | // const element = array[1]; 40 | // console.log(element); // Output: 2 41 | 42 | 43 | // Q5)How do you remove the last element from an array in JavaScript? 44 | 45 | // Answer: 46 | 47 | // const array = [1, 2, 3]; 48 | // const removedElement = array.pop(); 49 | // console.log(array); // Output: [1, 2] 50 | // console.log(removedElement); // Output: 3 51 | 52 | 53 | // Q6)How do you find the index of a specific element in an array? 54 | 55 | // Answer: 56 | 57 | // const array = [1, 2, 3, 4, 5]; 58 | // const index = array.indexOf(3); 59 | // console.log(index); // Output: 2 60 | 61 | 62 | // Q7)How do you concatenate two arrays in JavaScript? 63 | 64 | // Answer: 65 | 66 | // const array1 = [1, 2, 3]; 67 | // const array2 = [4, 5, 6]; 68 | // const concatenatedArray = array1.concat(array2); 69 | // console.log(concatenatedArray); // Output: [1, 2, 3, 4, 5, 6] 70 | 71 | 72 | // Q8)How do you check if an element exists in an array? 73 | 74 | // Answer: 75 | 76 | // const array = [1, 2, 3, 4, 5]; 77 | // const elementExists = array.includes(3); 78 | // console.log(elementExists); // Output: true 79 | 80 | 81 | // Q9)How do you find the maximum value in an array? 82 | 83 | // Answer: 84 | 85 | // const array = [4, 2, 7, 5, 1]; 86 | // const max = Math.max(...array); 87 | // console.log(max); // Output: 7 88 | 89 | 90 | // Q10)How do you reverse the order of elements in an array? 91 | 92 | // Answer: 93 | 94 | // const array = [1, 2, 3, 4, 5]; 95 | // array.reverse(); 96 | // console.log(array); // Output: [5, 4, 3, 2, 1] -------------------------------------------------------------------------------- /Ch 6 JS In Browser.js: -------------------------------------------------------------------------------- 1 | // Element Tab -> All Element 2 | // console Tab -> All The Error Plus Logs 3 | // Network Tab -> All The Network Request And Requirement 4 | 5 | // External File For Js -> File Cache Ho Jati he So Website Fast Work Karti He 6 | // We Can Add Js In Script Tag Also 7 | // 8 | // 9 | 10 | // Separation Of Concern and Cashing 11 | 12 | // Js Console Object 13 | // console.log(console) 14 | // console.error(error) 15 | // console.assert(assert) 16 | // console.clear() 17 | // console.table(table) 18 | // console.warn(warn) 19 | // console.info(info) 20 | // console.time(time) 21 | // console.timeEnd(timeEnd) 22 | 23 | // List All Method 24 | // console.log(console) 25 | 26 | // Output And Return Type Is There 27 | // console.log("Hey Darshan") 28 | // Output : 29 | // Hey Darshan 30 | // Undefined 31 | 32 | // Alert Prompt And Confirm 33 | // Alert -> Alert Box Show Karta Hai 34 | // Prompt -> Prompt Box Show Karta Hai -> Input Lene Ke Liye 35 | // Confirm -> Confirm Box Show Karta Hai -> Yes Or No Lene Ke Liye 36 | 37 | // alert("Enter The Value Of A") 38 | // let a = prompt("Enter A Here: ") 39 | // let a = prompt("Enter A Here: ", "578") // Default Value 40 | // document.write(a) 41 | 42 | 43 | // Confirm -> Yes Or No Lene Ke Liye 44 | // let write = confirm("Do You Want To Write It To The Page") 45 | // if (write) { 46 | // document.write(a) 47 | // } else { 48 | // document.write("Please Allow Me To Write") 49 | // } 50 | 51 | // This Will Stop Screen Execution Thats Why Not Suggested To Use That In User Side Plus Look Like Old Vintage Website So -> Use In Admin Panel 52 | 53 | // BOM And DOM 54 | 55 | // BOM -> Browser Object Model 56 | // DOM -> Document Object Model 57 | console.log(window) 58 | // window.console.log(window) -> Same Work Above 59 | 60 | // window is global object under that -> Bom , Dom , Js Core Feature Lies 61 | 62 | // Apke Pure HTML Page ko Document Represent Karta Hai -> Pure Page Ka Object Banke Usko Document Name De Diya Gaya He 63 | console.log(document) 64 | document.body.style.background = "yellow" 65 | 66 | 67 | 68 | // BOM (Browser Object Model): 69 | // The Browser Object Model represents the browser window or tab itself. It provides additional objects and properties that allow you to control the browser's behavior and interact with the user. The window object acts as the global object in JavaScript and serves as the entry point to the BOM. It provides properties and methods to control the browser's behavior, such as window.location to manipulate the URL, window.alert() to display alert messages, and window.open() to open new browser windows or tabs. 70 | 71 | 72 | // Location href = "https://dpvasani56.com" -> Redirect To Another URL 73 | 74 | // console.log(window) => All Method 75 | // Window Object -> Global Object 76 | -------------------------------------------------------------------------------- /Ch 6 JavaScript In Browser Practice Set.js: -------------------------------------------------------------------------------- 1 | // Ch 6 JavaScript In Browser Practice Set 2 | 3 | // Q1)How can you log a message to the console using the console object? 4 | 5 | // console.log("Hello, World!"); 6 | 7 | 8 | // Q2)How can you display an error message in the console using the console object? 9 | 10 | // console.error("An error occurred."); 11 | 12 | 13 | // Q3)How can you clear the console using the console object? 14 | 15 | // console.clear(); 16 | 17 | 18 | // Q4)How can you log a warning message to the console using the console object? 19 | 20 | // console.warn("This is a warning."); 21 | 22 | 23 | // Q5)How can you display tabular data as a table in the console using the console object? 24 | 25 | // const data = [ 26 | // { name: "John", age: 25 }, 27 | // { name: "Jane", age: 30 }, 28 | // { name: "Bob", age: 35 } 29 | // ]; 30 | // console.table(data); 31 | 32 | // Q6)How can you write an error message to the console if a condition is false using the console object? 33 | 34 | // const value = 10; 35 | // console.assert(value > 20, "Value should be greater than 20."); 36 | 37 | 38 | // Q7)How can you measure the time taken to execute a block of code using the console object? 39 | 40 | // console.time("Timer"); 41 | // // Code block to measure execution time 42 | // console.timeEnd("Timer"); 43 | 44 | 45 | // Q8)How can you prompt the user to enter their name and log it to the console using the prompt function? 46 | 47 | // const name = prompt("Enter your name:"); 48 | // console.log("Hello, " + name + "!"); 49 | 50 | 51 | // Q9)How can you display an alert box with a message to the user using the alert function? 52 | 53 | // alert("This is an alert message."); 54 | 55 | 56 | // Q10)How can you display a confirm dialog box and log the user's choice to the console using the confirm function? 57 | 58 | // const result = confirm("Are you sure you want to delete this item?"); 59 | // if (result === true) { 60 | // console.log("Item deleted."); 61 | // } else { 62 | // console.log("Deletion cancelled."); 63 | // } -------------------------------------------------------------------------------- /Ch 6 JavaScript In Browser.js: -------------------------------------------------------------------------------- 1 | // JavaScript In Browser 2 | // Semicolon Are Optional 3 | // JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. 4 | // JS -> Initially Created To Make Web Pages 5 | // Browser Has Embedded Engine -> JavaScript Engine or JavaScript Run Time 6 | // JS Ability In Browser Is Very Limited 7 | 8 | 9 | // Developer Tool -> Every Browser Has This -> Make Developer Life Easier 10 | 11 | 12 | // Element - Console - Network 13 | // All HTML Element - All Error + Log - All Network Request 14 | 15 | 16 | // Use JS In Browser 17 | 18 | // Scripts can be placed in the , or in the section of an HTML page, or in both. 19 | // To use JavaScript in a web page, you can embed it directly within the HTML document. 20 | 21 | // Inline Script: JavaScript code can be placed directly within the 27 | 28 | 29 | // External Script: JavaScript code can also be stored in an external file and linked to the HTML document using the This Must Be In Body Tag 32 | 33 | 34 | // Example Of JS In Browser 35 | 36 | // 37 | // 38 | // 39 | // JavaScript in the Browser 40 | // 41 | // 42 | //

Hello, World!

43 | // 44 | 45 | // 58 | // 59 | // 60 | 61 | 62 | // Console Object Method 63 | 64 | 65 | // The console object in JavaScript provides a set of methods that allow developers to interact with the browser's console. These methods are useful for logging messages, debugging code, and monitoring the execution of JavaScript code. Here are some commonly used methods of the console object along with examples: 66 | 67 | // console.log(console) -> List All Console Method 68 | 69 | // External JS is Better To Use -> Separation Of Concerns & Browser Caching -> Browser Save That FIle SO We Not Load Again It 70 | 71 | // log(): Logs a message to the console. 72 | 73 | // console.log('Hello, World!'); // Output: Hello, World! 74 | 75 | 76 | // error(): Logs an error message to the console. 77 | 78 | // console.error('An error occurred.'); // Output: An error occurred. 79 | 80 | 81 | // warn(): Logs a warning message to the console. 82 | 83 | // console.warn('This is a warning.'); // Output: This is a warning. 84 | 85 | 86 | // info(): Logs an informational message to the console. 87 | 88 | // // Output: This is an information. 89 | 90 | 91 | // debug(): Logs a debug message to the console. 92 | 93 | // console.debug('Debugging information.'); // Output: Debugging information. 94 | 95 | 96 | // assert(): Writes an error message to the console if the provided condition is false. 97 | 98 | // const value = 10; 99 | // console.assert(value > 20, 'Value should be greater than 20.'); // Output: Value should be greater than 20. 100 | 101 | 102 | // clear(): Clears the console. 103 | 104 | // console.clear(); // Clears the console 105 | 106 | 107 | // table(): Displays tabular data as a table in the console. 108 | 109 | // const data = [ 110 | // { name: 'John', age: 25 }, 111 | // { name: 'Jane', age: 30 }, 112 | // { name: 'Bob', age: 35 } 113 | // ]; 114 | // console.table(data); 115 | // Output: 116 | // ┌─────┬──────┬─────┐ 117 | // │ (index) │ name │ age │ 118 | // ├─────┼──────┼─────┤ 119 | // │ 0 │ 'John' │ 25 │ 120 | // │ 1 │ 'Jane' │ 30 │ 121 | // │ 2 │ 'Bob' │ 35 │ 122 | // └─────┴──────┴─────┘ 123 | // count(): Logs the number of times count() has been called with the provided label. 124 | 125 | // console.count('Counter'); // Output: Counter: 1 126 | // console.count('Counter'); // Output: Counter: 2 127 | // console.count('Another Counter'); // Output: Another Counter: 1 128 | // console.count('Counter'); // Output: Counter: 3 129 | 130 | 131 | // time() and timeEnd(): Measures the time taken to execute a block of code. 132 | 133 | // console.time('Timer'); 134 | // // Code block to measure execution time 135 | // console.timeEnd('Timer'); // Output: Timer: