├── .gitignore ├── Images ├── Class.png ├── Codingprocess.png ├── DOM_tree.png ├── How Js works.pdf ├── HowJsComplie.png ├── HowJsInterpret.png ├── HowJsJIT.png └── JITimg.png ├── Readme.md └── _config.yml /.gitignore: -------------------------------------------------------------------------------- 1 | .prettierrc -------------------------------------------------------------------------------- /Images/Class.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Chandraprakash-Darji/js-recap/bea9e31f3ee83842c3dece2abae5e9e4d16d68a3/Images/Class.png -------------------------------------------------------------------------------- /Images/Codingprocess.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Chandraprakash-Darji/js-recap/bea9e31f3ee83842c3dece2abae5e9e4d16d68a3/Images/Codingprocess.png -------------------------------------------------------------------------------- /Images/DOM_tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Chandraprakash-Darji/js-recap/bea9e31f3ee83842c3dece2abae5e9e4d16d68a3/Images/DOM_tree.png -------------------------------------------------------------------------------- /Images/How Js works.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Chandraprakash-Darji/js-recap/bea9e31f3ee83842c3dece2abae5e9e4d16d68a3/Images/How Js works.pdf -------------------------------------------------------------------------------- /Images/HowJsComplie.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Chandraprakash-Darji/js-recap/bea9e31f3ee83842c3dece2abae5e9e4d16d68a3/Images/HowJsComplie.png -------------------------------------------------------------------------------- /Images/HowJsInterpret.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Chandraprakash-Darji/js-recap/bea9e31f3ee83842c3dece2abae5e9e4d16d68a3/Images/HowJsInterpret.png -------------------------------------------------------------------------------- /Images/HowJsJIT.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Chandraprakash-Darji/js-recap/bea9e31f3ee83842c3dece2abae5e9e4d16d68a3/Images/HowJsJIT.png -------------------------------------------------------------------------------- /Images/JITimg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Chandraprakash-Darji/js-recap/bea9e31f3ee83842c3dece2abae5e9e4d16d68a3/Images/JITimg.png -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # Notes for Javascript 2 | 3 | **[Live Site Link](https://chandraprakash-darji.github.io/js-recap/)** 4 | 5 | _(Credits [Jonas Schmedtmann](https://twitter.com/jonasschmedtman) JS Course for amazing content that i learned)_ 6 | 7 | **Navigate to the Topic** 8 | 9 | - [Notes for Javascript](#notes-for-javascript) 10 | - [Basis of JS](#basis-of-js) 11 | - [The 7 Primitive Data types](#the-7-primitive-data-types) 12 | - [Operators in JS](#operators-in-js) 13 | - [Arithmetic Operators](#arithmetic-operators) 14 | - [Assignment Operators](#assignment-operators) 15 | - [Comparison Operators](#comparison-operators) 16 | - [Logical Operators](#logical-operators) 17 | - [Ternary Operators](#ternary-operators) 18 | - [Spread/Rest Operator](#spreadrest-operator) 19 | - [Template literals (Template strings)](#template-literals-template-strings) 20 | - [Conditional Statment ( if-Else )](#conditional-statment--if-else-) 21 | - [Type Conversion and Coercion](#type-conversion-and-coercion) 22 | - [Type Conversion](#type-conversion) 23 | - [Falsy values](#falsy-values) 24 | - [Truely Value](#truely-value) 25 | - [Type Coercion](#type-coercion) 26 | - [Switch Statment](#switch-statment) 27 | - [Functions](#functions) 28 | - [Default Arguments](#default-arguments) 29 | - [How passing argument Works :: value vs. Refrence](#how-passing-argument-works--value-vs-refrence) 30 | - [First Class and Higher Order Function](#first-class-and-higher-order-function) 31 | - [Some Properties of First-Class Functions](#some-properties-of-first-class-functions) 32 | - [Higher Order Functions](#higher-order-functions) 33 | - [Some Properties of Higher-Order Functions](#some-properties-of-higher-order-functions) 34 | - [Function that recevies another function](#function-that-recevies-another-function) 35 | - [Function that returns a new function](#function-that-returns-a-new-function) 36 | - [Implimentation](#implimentation) 37 | - [Function Accepting CallBacks](#function-accepting-callbacks) 38 | - [Function Returninng the Function](#function-returninng-the-function) 39 | - [Call Method](#call-method) 40 | - [Apply Method](#apply-method) 41 | - [Bind Method](#bind-method) 42 | - [Imediately Invoked Functions](#imediately-invoked-functions) 43 | - [Arrays](#arrays) 44 | - [Objects](#objects) 45 | - [Sets](#sets) 46 | - [Maps](#maps) 47 | - [Working With String](#working-with-string) 48 | - [Data Strucutres](#data-strucutres) 49 | - [List of data Strucures](#list-of-data-strucures) 50 | - [Sources of Data](#sources-of-data) 51 | - [Usess of Arrays](#usess-of-arrays) 52 | - [Usess of Sets](#usess-of-sets) 53 | - [Usess of Object](#usess-of-object) 54 | - [Usess of Maps](#usess-of-maps) 55 | - [Basic Data Structures](#basic-data-structures) 56 | - [Numbers](#numbers) 57 | - [BigInt](#bigint) 58 | - [Date](#date) 59 | - [Intl NameSpace](#intl-namespace) 60 | - [Loops](#loops) 61 | - [For Loops](#for-loops) 62 | - [For of loops](#for-of-loops) 63 | - [ForEach loops](#foreach-loops) 64 | - [Nested Loops](#nested-loops) 65 | - [While loop](#while-loop) 66 | - [Loop Control Statments](#loop-control-statments) 67 | - [Continue](#continue) 68 | - [Break](#break) 69 | - [Timers](#timers) 70 | - [SetTimeout](#settimeout) 71 | - [setInterval](#setinterval) 72 | - [DOM Manuplication](#dom-manuplication) 73 | - [Accessing Dom Elements](#accessing-dom-elements) 74 | - [Dom traversing](#dom-traversing) 75 | - [Create New DOM Elements](#create-new-dom-elements) 76 | - [Add Elements to the DOM](#add-elements-to-the-dom) 77 | - [Remove Html Element](#remove-html-element) 78 | - [Add/Remove/Toggle/Check Classes](#addremovetogglecheck-classes) 79 | - [Updating Styles Using Dom](#updating-styles-using-dom) 80 | - [Changing the Atributes](#changing-the-atributes) 81 | - [Events in DOM](#events-in-dom) 82 | - [Short Circuiting](#short-circuiting) 83 | - [Nullish Coalescing Operator](#nullish-coalescing-operator) 84 | - [OOPS](#oops) 85 | - [Class](#class) 86 | - [THE 4 FUNDAMENTAL OOP PRINCIPLES](#the-4-fundamental-oop-principles) 87 | - [Abstraction](#abstraction) 88 | - [Encapsulation](#encapsulation) 89 | - [Inheritance](#inheritance) 90 | - [Polymorphism](#polymorphism) 91 | - [Prototypal inheritance](#prototypal-inheritance) 92 | - [3 WAYS OF IMPLEMENTING PROTOTYPAL INHERITANCE IN JAVASCRIPT](#3-ways-of-implementing-prototypal-inheritance-in-javascript) 93 | - [Constructor Function](#constructor-function) 94 | - [Prototypes](#prototypes) 95 | - [THE PROTOTYPE CHAIN](#the-prototype-chain) 96 | - [ES2015 Classes](#es2015-classes) 97 | - [Getters and Setters](#getters-and-setters) 98 | - [Object.create()](#objectcreate) 99 | - [InHertience between Classes](#inhertience-between-classes) 100 | - [Encapsulation](#encapsulation-1) 101 | - [Chaining in Class methods](#chaining-in-class-methods) 102 | - [Class in one Image](#class-in-one-image) 103 | - [SYNCHRONOUS CODE](#synchronous-code) 104 | - [ASYNCHRONOUS CODE](#asynchronous-code) 105 | - [WHAT ARE AJAX CALLS?](#what-are-ajax-calls) 106 | - [WHAT IS AN API?](#what-is-an-api) 107 | - [WHAT HAPPENS WHEN WE ACCESS A WEB SERVER](#what-happens-when-we-access-a-web-server) 108 | - [WHAT ARE PROMISES?](#what-are-promises) 109 | - [Fetch API](#fetch-api) 110 | - [THE PROMISE LIFECYCLE](#the-promise-lifecycle) 111 | - [Building the Promise](#building-the-promise) 112 | - [Async Await Function](#async-await-function) 113 | - [Promise Combinator](#promise-combinator) 114 | - [AN OVERVIEW OF MODULES](#an-overview-of-modules) 115 | - [WHY MODULES?](#why-modules) 116 | - [NATIVE JAVASCRIPT (ES6) MODULES](#native-javascript-es6-modules) 117 | - [HOW ES6 MODULES ARE IMPORTED](#how-es6-modules-are-imported) 118 | - [Import and Export Modules](#import-and-export-modules) 119 | - [Developer Skills](#developer-skills) 120 | - [HOW TO FAIL 🤦 AT LEARNING HOW TO CODE](#how-to-fail--at-learning-how-to-code) 121 | - [HOW TO SUCCEED 🎉 AT LEARNING HOW TO CODE](#how-to-succeed--at-learning-how-to-code) 122 | - [HOW TO FAIL 🤦 AT SOLVING PROBLEMS](#how-to-fail--at-solving-problems) 123 | - [4 STEPS FRAMEWORK TO SOLVE ANY PROBLEM](#4-steps-framework-to-solve-any-problem) 124 | - [WHAT IS A SOFTWARE BUG?](#what-is-a-software-bug) 125 | - [THE DEBUGGING PROCESS](#the-debugging-process) 126 | 127 | ## Basis of JS 128 | 129 | 1. On page Script 130 | 131 | ```html 132 | 135 | ``` 136 | 137 | 2. Include external JS file 138 | 139 | ```html 140 | 141 | ``` 142 | 143 | 3. Output 144 | 145 | ```js 146 | console.log(a); // write to the browser console 147 | document.write(a); // write to the HTML 148 | alert(a); // output in an alert box 149 | confirm('Really?'); // yes/no dialog, returns true/false depending on user click 150 | prompt('Your age?', '0'); // input dialog. Second argument is the initial value 151 | ``` 152 | 153 | 4. Comments 154 | 155 | ```js 156 | /* Multi line 157 | comment */ 158 | // One line 159 | ``` 160 | 161 | 6. Strict mode 162 | 163 | ```js 164 | 'use strict'; // Use strict mode to write secure code 165 | x = 1; // Throws an error because variable is not declared 166 | ``` 167 | 168 | ## The 7 Primitive Data types 169 | 170 | - To check the Data type of any Varible / Value 171 | 172 | ```js 173 | console.log(typeof 'ChandraPrakash'); 174 | ``` 175 | 176 | - Way of Declaring Variables 177 | 178 | ```js 179 | var a; // variable 180 | var a = 1, 181 | b = 2, 182 | c = a + b; // one line 183 | const PI = 3.14; // constant 184 | let z = 'zzz'; // block scope local variable 185 | 186 | ('use strict'); // Use strict mode to write secure code 187 | x = 1; // Throws an error because variable is not declared 188 | // Creates property on global scope. [Not reccomend to wright Variable without Declaring] 189 | ``` 190 | 191 | 1. Number: Floating point numbers -> Used for decimal and integers. 192 | 193 | ```js 194 | let age = 23; 195 | console.log(typeof age); 196 | ``` 197 | 198 | 2. String: Sequence of characters -> Used for text. 199 | 200 | ```js 201 | let firstName = 'ChandraPrakash'; 202 | console.log(typeof firstname); 203 | ``` 204 | 205 | 3. Boolean: Logical type that can only be true or false -> Used for taking decisiions. 206 | 207 | ```js 208 | let fullAge = true; 209 | console.log(typeof fullAge); 210 | ``` 211 | 212 | 4. Undefined Value by a variables is not yet defind("empty value"). 213 | 214 | ```js 215 | let children; 216 | console.log(typeof children); 217 | ``` 218 | 219 | 5. Null: Also means 'empty value'. 220 | 221 | ```js 222 | let myNull = null; 223 | console.log(typeof myNull); 224 | ``` 225 | 226 | 6. Symbol (ES2015): Value that is unquie and cannot be changed _[Not useful for now]_. 227 | 228 | 7. Biglnt (ES2020): Larger integers than the Number type can hold. 229 | 230 | ## Operators in JS 231 | 232 | - [Arithmetic Operators](#arithmetic-operators) 233 | - [Assignment Operators](#assignment-operators) 234 | - [Comparison Operators](#comparison-operators) 235 | - [Logical Operators](#logical-operators) 236 | - [Ternary Operators](#ternary-operators) 237 | 238 | ### Arithmetic Operators 239 | 240 | ```js 241 | console.log(10 + 5); // Addition -> 15 242 | console.log(10 - 5); // Subtraction -> 5 243 | console.log(10 / 2); // Division -> 5 244 | console.log(10 * 4); // Multply -> 40 245 | console.log(7 % 2); // Modulas -> 1 246 | console.log(2 ** 4); // 16 247 | console.log(2++); // Increment -> 3 248 | console.log(2--); // Decrement -> 1 249 | ``` 250 | 251 | - Post and Pre Increment/Decrement 252 | 253 | ```js 254 | let x = 5; 255 | // x++, it will increase the value of x when the program control goes to the next statement. 256 | // ++x, it will increase the value of x there only 257 | 258 | x++; //post-increment, x will be 5 here and 6 in the next line 259 | ++x; //pre-increment, x will be 7 here 260 | x--; //post-decrement, x will be 7 here and 6 in the next line 261 | --x; //pre-decrement, x will be 5 here 262 | ``` 263 | 264 | ### Assignment Operators 265 | 266 | ```js 267 | let x = 10 + 5; // Assigns right operand value to the left operand. -> 15 268 | x += 10; // Sum left and right operand and stores in left operand -> 25 269 | x *= 4; // Multiply left and right operand and stores in left operand -> 100 270 | // [ " -= " for Subtraction , " /= " for Division , " %= " for Modulas ] 271 | x++; // 101 272 | x--; // 100 273 | x--; // 99 274 | console.log(x); // 99 275 | ``` 276 | 277 | ### Comparison Operators 278 | 279 | ```js 280 | console.log(40 == 8); // Compares the equality of two operands without considering type. 281 | console.log(40 === 8); // Compares equality of two operands with type. 282 | console.log(40 != 8); // Compares inequality of two operands without considering type. 283 | console.log(40 !== 8); // Compares inequality of two operands with type. 284 | console.log(40 < 8); // Less Than / return true if 40 <> 8 285 | console.log(40 >= 8); // Greater Than equal to / return true if 40 >= 8 286 | console.log(40 <= 8); // Less Than equal to / return true if 40 <>= 8 287 | ``` 288 | 289 | ### Logical Operators 290 | 291 | ```js 292 | let a = 5, 293 | b = 10; 294 | 295 | a != b && a < b; // returns true. // Both Condition should true. 296 | a > b || a == b; // returns false // One Condition should true 297 | a < b || a == b; // returns true 298 | !(a < b); // returns false // Inverse the Solution true <-> false 299 | !(a > b); // returns true 300 | ``` 301 | 302 | ### Ternary Operators 303 | 304 | The second part (after ? and before :) will be executed if the condition turns out to be true. Suppose, the condition returns false, then the third part (after :) will be executed. 305 | 306 | ```js 307 | let a = 10, 308 | b = 5; 309 | 310 | var c = a > b ? a : b; // value of c would be 10 311 | var d = a > b ? b : a; // value of d would be 5 312 | ``` 313 | 314 | ### Spread/Rest Operator 315 | 316 | ```js 317 | // Unpacking Array at Once by spread Operator 318 | const arr = [7, 8, 9]; 319 | const badNewArr = [1, 2, arr[0], arr[1], arr[2]]; // [1, 2, 7, 8, 9] 320 | 321 | const newArr = [1, 2, ...arr]; // [1, 2, 7, 8, 9] 322 | // spread operator is comma seprated Value -> It can be Used for all iterable ( string , array , map , sets ) But not Objects 323 | // this are completing new array 324 | 325 | console.log(newArr); // [1, 2, 7, 8, 9] 326 | console.log(...newArr); // 1 2 7 8 9 327 | 328 | // Spread operator on String 329 | const str = 'Jonas'; 330 | const letters = [...str, '', 'S.']; // ['J', 'o', 'n', 'a', 's', '', 'S.'] 331 | 332 | // Spread operator are only Used when multiple Values can enter... like you can't use in tmeplte litral 333 | 334 | // SPREAD, beacuse it is on RIGHT side of = -> value seprated by commas 335 | const arr = [1, 2, ...[3, 4]]; 336 | console.log(arr); // [1, 2, 3, 4] 337 | 338 | // REST, beacuse on LEFT side of = -> variable seprated by Comma 339 | const [a, b, ...others] = [1, 2, 3, 4, 5, 6]; 340 | console.log(a, b, others); // 1 2 [3, 4, 5, 6] 341 | 342 | const [pizza, resto, ...otherFood] = [ 343 | ...restaurant.mainMenu, 344 | ...restaurant.starterMenu, 345 | ]; 346 | console.log(pizza, resto, otherFood); // Pizza Pasta ['Risotto', 'Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'] 347 | 348 | // Objects 349 | const { sat, ...weekdays } = restaurant.openingHours; 350 | console.log(sat, weekdays); // {open: 0, close: 24} {thu: {…}, fri: {…}} 351 | 352 | // FUNCTIONS 353 | const add = function (...numbers) { 354 | let sum = 0; 355 | for (let i = 0; i < numbers.length; i++) sum += numbers[i]; 356 | console.log(sum); 357 | }; 358 | add(2, 3); 359 | add(2, 3, 4); 360 | add(2, 3, 4, 5); 361 | add(2, 4, 54, 45); 362 | 363 | const x = [2, 5, 1, 51, 54, 54, 5]; 364 | add(...x); 365 | 366 | // Copy Array 367 | const myArr = [1, 2, 3]; 368 | const myCopy = [...myArr]; // All elemt of myArr will be Copied 369 | ``` 370 | 371 | ## Template literals (Template strings) 372 | 373 | ```js 374 | // Untagged, these create strings: 375 | `string text``string text line 1 376 | string text line 2` // Multi line String 377 | `string text ${expression} string text`; // access any veriable by ${variable_name} 378 | ``` 379 | 380 | - Without Template Literals 381 | 382 | ```js 383 | let a = 5, 384 | b = 10; 385 | console.log('Fifteen is ' + (a + b) + ' and \n not ' + (2 * a + b) + '.'); 386 | // "Fifteen is 15 and 387 | // not 20." 388 | ``` 389 | 390 | - With Template Literals 391 | 392 | ```js 393 | let a = 5, 394 | b = 10; 395 | console.log(`Fifteen is ${a + b} and 396 | not ${2 * a + b}.`); 397 | // "Fifteen is 15 and 398 | // not 20." 399 | ``` 400 | 401 | ## Conditional Statment ( if-Else ) 402 | 403 | ```js 404 | const age = 19; 405 | if (age >= 18) { 406 | // logical condition 407 | status = 'Eligible for driving License.'; // executed if condition is true 408 | } else { 409 | // else block is optional 410 | const yearsLeft = 18 - age; 411 | status = `Not eligible for driving License. Wait for ${yearsLeft} years`; 412 | // executed if condition is false 413 | } 414 | ``` 415 | 416 | ## Type Conversion and Coercion 417 | 418 | - [Type Conversion](#type-conversion) Changing type of the Data explicitly. 419 | - [Type Coercion](#type-coercion) Javascript changing type of the Data implicitly. 420 | 421 | ### Type Conversion 422 | 423 | ```js 424 | const inputYear = '1991'; 425 | // number() for String to Number 426 | console.log(Number(inputYear), inputYear); // 1991 '1991' 427 | console.log(Number(inputYear) + 18); // 2009 428 | 429 | console.log(Number('ChandraPrakash')); // NaN 430 | 431 | // String() for Number to String 432 | console.log(String(23)); // 23 433 | ``` 434 | 435 | #### Falsy values 436 | 437 | [ 0 , "" , undefined , null , NaN , false ] are false if they are converted to Boolean 438 | 439 | ```js 440 | console.log(Boolean(0)); // false 441 | console.log(Boolean('')); // false 442 | console.log(Boolean(NaN)); // false 443 | console.log(Boolean(false)); // false 444 | console.log(Boolean(undefined)); // false 445 | console.log(Boolean(null)); // false 446 | ``` 447 | 448 | #### Truely Value 449 | 450 | All values are truely if it is not [ 0 , "" , undefined , null , NaN , false ] 451 | 452 | ### Type Coercion 453 | 454 | ```js 455 | // 23 Automatically converted to String while logging the String. 456 | // " + " convert number to String 457 | console.log('I am ' + 23 + ' years old.'); // I am 23 years old. 458 | 459 | // " - " , " / " , " * " and also logical operators 460 | // convert String to Number 461 | console.log('23' - '10' - 3); // 10 462 | console.log('23' > '10'); // true 463 | 464 | // Example 465 | let n = '1' + 1; // 11 466 | n = n - 1; // 10 467 | console.log(n); 468 | ``` 469 | 470 | ## Switch Statment 471 | 472 | ```js 473 | switch ( 474 | new Date().getDay() // input is current day 475 | ) { 476 | case 6: // if (day == 6) 477 | text = 'Saturday'; 478 | break; 479 | case 0: // if (day == 0) 480 | text = 'Sunday'; 481 | break; 482 | default: 483 | // else... 484 | text = 'Whatever'; 485 | } 486 | ``` 487 | 488 | ## Functions 489 | 490 | ```js 491 | // Function Declaration // Pros we can call Before Declaration 492 | function addNumbers(a, b) { 493 | return a + b; 494 | } 495 | x = addNumbers(1, 2); 496 | console.log(x); // 3 497 | 498 | // Function Expression // Can't call before Declration 499 | const birthYear = 2002; 500 | const calcAge = function (birthYear) { 501 | return 2022 - birthYear; 502 | }; 503 | console.log(calcAge(birthYear)); // 20 504 | 505 | // Arow function 506 | const calcAge2 = birthYear => 2022 - birthYear; 507 | 508 | // Arrow functions with more than one Variablea 509 | const yearsUntilRetirment = (birthYear, firstName) => { 510 | const age = 2022 - birthYear; 511 | const retirment = 65 - age; 512 | return `${firstName} retires in ${retirment} years`; 513 | }; 514 | console.log(yearsUntilRetirment(2002, 'Chandraprakash')); 515 | ``` 516 | 517 | ### Default Arguments 518 | 519 | ```js 520 | const bookings = []; 521 | const createBooking = function ( 522 | flightNum, 523 | numPassenger = 1, // default Variables 524 | price = 199 * numPassenger // Using Expression on alredy defined variable 525 | ) { 526 | const booking = { 527 | flightNum, // Direct object declaration 528 | numPassenger, 529 | price, 530 | }; 531 | console.log(booking); 532 | bookings.push(booking); 533 | }; 534 | createBooking('LH123'); // Passing only one arrgument 535 | createBooking('LH123', 2, 800); 536 | createBooking('LH123', 2); // Calculating price value depending upon passneger 537 | createBooking('LH123', 5); 538 | createBooking('LH123', undefined, 50); // set any value to undefined to skip that value and make it default 539 | console.log(bookings); // Loging all the booking 540 | ``` 541 | 542 | ### How passing argument Works :: value vs. Refrence 543 | 544 | ```js 545 | const flight = 'LH123'; 546 | const jonas = { 547 | name: 'Jonas Schmendtmann', 548 | passport: 646513132, 549 | }; 550 | 551 | const checkIn = function (flightNum, passneger) { 552 | flightNum = 'LH999'; 553 | passneger.name = 'Mr.' + passneger.name; 554 | 555 | if (passneger.passport === 646513132) { 556 | // alert('CheckIn'); 557 | } else { 558 | // alert('Wrong Passport'); 559 | } 560 | }; 561 | checkIn(flight, jonas); 562 | console.log(flight, jonas); // LH123 {name: 'Mr.Jonas Schmendtmann', passport: 646513132} 563 | 564 | // When we pass any primitive data type the copy of data is passed 565 | // But When we pass Object in Function the Refrence is passed not the copy with that ::: 566 | // when we change in the function it change the refrence and Orignal One Becuse it is Saved in memorry Heap 567 | ``` 568 | 569 | ### First Class and Higher Order Function 570 | 571 | - First Class Function => JavaScript treats function as first-class Citizen => 572 | - This means that functions are simply values => 573 | - Functions are just another Object 574 | - Just a concept that a Programming Language as or not ::: 575 | 576 | #### Some Properties of First-Class Functions 577 | 578 | - **Store Functions in Variables or Properties** 579 | 580 | ```js 581 | const add = (a, b) => a + b; 582 | ``` 583 | 584 | ```js 585 | const conuter = { 586 | value: 23, 587 | inc: function () { 588 | this.value++; 589 | }, 590 | }; 591 | ``` 592 | 593 | - **Pass functions as Argumnets to OTHER functions** 594 | 595 | ```js 596 | const greet = () => console.log('hey Chandr Prakash'); 597 | btnClose.addEventListener('click', greet); 598 | ``` 599 | 600 | - **Return Functon from Function** 601 | - **Call methods on functions:** 602 | 603 | ```js 604 | counter.inc.bind(someOtherObject); 605 | ``` 606 | 607 | ### Higher Order Functions 608 | 609 | - A function that **receives** another function as an argument, that **return** a new function, or **both** 610 | - Is in practise when lang => Supports the **First class Function** 611 | 612 | #### Some Properties of Higher-Order Functions 613 | 614 | ##### Function that recevies another function 615 | 616 | ```js 617 | const greet = () => console.log("Hey ChandrPrakash); 618 | btnClose.addEventListener('click', greet) 619 | // addEventListener is a Higher-order function 620 | // greet is CallBack Function 621 | ``` 622 | 623 | ##### Function that returns a new function 624 | 625 | ```js 626 | function count() { 627 | // ⇑ Higher Order Function 628 | let counter = 0; 629 | return function () { 630 | // ⇑ Returned Function 631 | counter++; 632 | }; 633 | } 634 | ``` 635 | 636 | #### Implimentation 637 | 638 | ##### Function Accepting CallBacks 639 | 640 | ```js 641 | const oneWord = function (str) { 642 | return str.replace(/ /g, '').toLowerCase(); 643 | }; 644 | const upperFirstWord = function (str) { 645 | const [first, ...other] = str.split(' '); 646 | return [first.toUpperCase(), ...other].join(' '); 647 | }; 648 | 649 | // Higher Order Functions 650 | const transformer = function (str, fn) { 651 | // fn is callback function 652 | // Higher order Function does not consist of Main logic 653 | // It depend Upon the lower order function 654 | // Higher Order function doesn't know what to do 655 | console.log(`Orignal String: ${str}`); 656 | console.log(`Transformed String: ${fn(str)}`); 657 | 658 | console.log(`Transformed by: ${fn.name}`); 659 | }; 660 | 661 | transformer('JavaScript is the Best', upperFirstWord); 662 | // Orignal String: JavaScript is the Best 663 | // Transformed String: JAVASCRIPT is the Best 664 | // Transformed by: upperFirstWord 665 | transformer('JavaScript is the Best', oneWord); 666 | // Orignal String: JavaScript is the Best 667 | // Transformed String: javascriptisthebest 668 | // Transformed by: oneWord 669 | 670 | // Js uses callbacks all the Time 671 | const high5 = function () { 672 | console.log('👋'); 673 | }; 674 | 675 | document.body.addEventListener('click', high5); 676 | ['Jonas', 'Martha', 'Adam'].forEach(high5); 677 | ``` 678 | 679 | ##### Function Returninng the Function 680 | 681 | ```js 682 | // Function Expression 683 | const greetExp = function (greeting) { 684 | return function (name) { 685 | console.log(`${greeting} ${name}`); 686 | }; 687 | }; 688 | const greetHey = greetExp('Hey'); 689 | greetHey('Jonas'); 690 | greetHey('Chandraprakash'); 691 | 692 | greetExp('Hello')('Chandra Prakash'); 693 | 694 | // Arrow Function ( confusing ) 695 | const greetArr = greeting => name => console.log(`${greeting} ${name}`); 696 | 697 | greetArr('Hi')('Chandra Prakash'); 698 | ``` 699 | 700 | ##### Call Method 701 | 702 | ```js 703 | const luthansa = { 704 | airline: 'luthansa', 705 | iataCode: 'LH', 706 | bookings: [], 707 | book(flightNum, name) { 708 | console.log( 709 | `${name} booked a seat on ${this.airline} flight ${this.iataCode}${flightNum}` 710 | ); 711 | this.bookings.push({ 712 | flight: `${this.iataCode}${flightNum}`, 713 | name, 714 | }); 715 | }, 716 | }; 717 | luthansa.book(234, 'Jonas Schmendtmann'); 718 | 719 | const eurowing = { 720 | name: 'Eurowings', 721 | iataCode: 'EW', 722 | bookings: [], 723 | }; 724 | 725 | const book = luthansa.book; 726 | 727 | // book(23, 'Sarah Williams'); // Here this keyword in book function will be undefined so it will bring Error 728 | // Book is Just a normal function not and method 729 | 730 | // Call Method 731 | book.call(eurowing, 543, 'Chandraprakash'); // Here we are settings that `this` keyword should point to eurowing 732 | 733 | book.call(luthansa, 654, 'ChandrPrakash'); 734 | ``` 735 | 736 | ##### Apply Method 737 | 738 | Takes two argument 1. this keyword Point 2. array of argument should pass to book fun. 739 | 740 | ```js 741 | const bookingData = [332, 'Mary Will']; 742 | book.apply(luthansa, bookingData); // Not Used More in Mordern JS 743 | console.log(luthansa); 744 | 745 | // apply alt. 746 | book.call(eurowing, ...bookingData); // Spread Opertaor Convert array to comma Sperated Values 747 | console.log(eurowing); 748 | ``` 749 | 750 | ##### Bind Method 751 | 752 | ```js 753 | 754 | // bind method creates new function ::: that functions ""this"" keyword points to the object that is binded 755 | const bookEW = book.bind(eurowing); 756 | bookEW(23, 'Stewen'); 757 | 758 | // Giving the default argument to the returned function 759 | const bookEW23 = book.bind(eurowing, 23); 760 | bookEW23('Chandraprakash'); 761 | 762 | // Practical Use 763 | luthansa.planes = 300; 764 | luthansa.buyPlane = function () { 765 | console.log(this); 766 | 767 | this.planes++; 768 | console.log(this.planes); 769 | }; 770 | 771 | // in Event handler the function passed in always point to the element we are giving event 772 | document.querySelector('.buy').addEventListener('click', luthansa.buyPlane); // NaN 773 | 774 | // We need to give the this keyword manualy 775 | document 776 | .querySelector('.buy') 777 | .addEventListener('click', luthansa.buyPlane.bind(luthansa)); 778 | // {airline: 'luthansa', iataCode: 'LH', bookings: Array(3), planes: 300, book: ƒ, …} 779 | // 301 780 | 781 | // Partial Application 782 | const addtax = (rate, value) => value + value \* rate; 783 | console.log(addtax(0.1, 100)); 784 | 785 | const addVAT = addtax.bind(null, 0.23); 786 | // addVAT = value => value + value \* .23 787 | 788 | console.log(addVAT(100)); 789 | console.log(addVAT(23)); 790 | 791 | const addtaxNoBind = function (rate) { 792 | return function (value) { 793 | return value + value \* rate; 794 | }; 795 | }; 796 | 797 | const rate23 = addtaxNoBind(0.23); 798 | console.log(rate23(100)); 799 | console.log(rate23(23)); 800 | 801 | ``` 802 | 803 | ### Imediately Invoked Functions 804 | 805 | ```js 806 | (function () { 807 | console.log('This Only Run Once'); 808 | })(); 809 | 810 | (() => { 811 | console.log('Arrow only once'); 812 | const isPrivate = 23; // Scoped Variable Cant't Accese from Outside 813 | })(); 814 | 815 | { 816 | const isPrivte = 40; // Private blovked Scoped 817 | var notPrivate = 46; // Not Privte Functional Scope 818 | } 819 | ``` 820 | 821 | ## Arrays 822 | 823 | ```js 824 | // Methoda 1 of declaring Arrays 825 | const friends = ['Ankit', 'Dave', 'Jonas']; 826 | console.log(friends); 827 | 828 | // Method 2 of Declaring Arrays 829 | const years = new Array(1991, 1992, 1993, 1994, 1995, 1996, 1997); 830 | console.log(years); 831 | 832 | // Access the Elements 833 | console.log(friends[0], years[3]); 834 | 835 | // length of Arrays 836 | console.log(friends.length); 837 | 838 | // Last item of Array 839 | console.log(friends[friends.length - 1]); 840 | 841 | // Changing Element 842 | friends[1] = 'Jay'; 843 | console.log(friends); 844 | 845 | // Diffrent type of Data 846 | const chandraPrakash = [ 847 | 'ChandraPrakash', 848 | 'Darji', 849 | 2022 - 2002, 850 | 'India', 851 | friends, 852 | ]; 853 | console.log(chandraPrakash); 854 | 855 | // Pushing Element 856 | const NewLength = friends.push('C2'); // Element is pushed and NewLenght is Returned 857 | console.log(friends, NewLength); 858 | 859 | // Push Element at index 0 860 | friends.unshift('Raj'); 861 | console.log(friends); 862 | 863 | // Remove Element 864 | const popedValue = friends.pop(); 865 | console.log(friends, popedValue); 866 | 867 | // Remove first Element 868 | friends.shift(); 869 | console.log(friends); 870 | 871 | // find Element 872 | console.log(friends.indexOf('Jay')); // 1 873 | console.log(friends.indexOf('Jay2')); // -1 means not Exist 874 | 875 | // check if exist 876 | console.log(friends.includes('Jay')); // true 877 | 878 | // Distructuring( Unpacking ) the Array 879 | const arr = [2, 3, 4]; 880 | const [x, y, z] = arr; 881 | console.log(x, y, z); // 2 3 4 882 | 883 | const categories = ['Italian', 'Pizzeria', 'Vegetarian', 'Organic']; 884 | const [main, , secondary] = categories; // mainn = "IOItalian" and secondary = "Vegetarian" 885 | [secondary, main] = [main, secondary]; // main <-> secondary 886 | 887 | const nested = [2, 3, [4, 5]]; 888 | const [i, , [j, k]] = nested; 889 | console.log(i, j, k); // 2 4 5 890 | 891 | const [p, q, r] = [2, 5]; // p = 2 ::: q = 5 ::: r = undefined 892 | const [p = 1, q = 1, r = 1] = [2]; // p = 2 ::: q = 1 ::: r = 1 893 | 894 | // 1. SLICE Method 895 | let arr = ['a', 'b', 'c', 'd', 'f']; 896 | console.log(arr.slice(2)); // element from 2 index to end :: ['c', 'd', 'f']] 897 | console.log(arr.slice(2, 4)); // element from 2 index to 3 ['c', 'd'] 898 | console.log(arr.slice(-2)); // negative number means from end of the array :: ['d', 'f'] 899 | console.log(arr.slice(2, 4)); // element from 2 index to 3 ['c', 'd'] 900 | console.log(arr.slice(2, -2)); // ["c"] 901 | console.log(arr.slice()); // full copy of orignal Array 902 | 903 | // 2. SPLICE 904 | console.log(arr.splice(2)); // [ "c", "d", "f" ] 905 | console.log(arr); // [ "a", "b" ] // Extracted element is removed 906 | 907 | // 3. REVERSE 908 | arr = ['a', 'b', 'c', 'd', 'f']; 909 | let arr2 = ['j', 'k', 'i', 'g']; 910 | 911 | console.log(arr2.reverse()); // Reverse the original array and return it 912 | console.log(arr2); // [ "g", "i", "k", "j" ] 913 | 914 | // 4. CONCAT 915 | const letters = arr.concat(arr2); // Adding 2 array :: didn't change orrignal 916 | console.log(letters); // [ "a", "b", "c", "d", "f", "g", "i", "k", "j" ]​ 917 | 918 | // 5. JOIN 919 | console.log(letters.join(' - ')); // a - b - c - d - f - g - i - k - j 920 | // Join array items by any seprater 921 | ``` 922 | 923 | **Map method** 924 | 925 | Map returns a new array containg the result of pplying operation on all original elements. 926 | 927 | In Map method also like forEach callback function ::: first argument -> element ::: second -> index ::: third argument -> Array. 928 | 929 | ```js 930 | // Map method :: Don't change Orignal Array 931 | const eurToUsd = 1.1; 932 | const moveUsd = movements.map(mov => mov * eurToUsd); 933 | 934 | console.log(movements); // [ 200, 450, -400, 3000, -650, -130, 70, 1300 ] 935 | console.log(moveUsd); // [ 220.00000000000003, 495.00000000000006, -440.00000000000006, 3300.0000000000005, -715.0000000000001, -143, 77, 1430.0000000000002 ] 936 | ``` 937 | 938 | **Filter Method** 939 | Filter returns a new array contaning the array elements that passed a specified text condition 940 | 941 | Returns the whole array matches the condition 942 | 943 | ```js 944 | const deposit = movements.filter(mov => mov > 0); 945 | const withdrawal = movements.filter(mov => mov < 0); 946 | 947 | console.log(movements); // [ 200, 450, -400, 3000, -650, -130, 70, 1300 ] 948 | console.log(deposit); // [ 200, 450, 3000, 70, 1300 ] 949 | console.log(withdrawal); // [ -400, -650, -130 ] 950 | ``` 951 | 952 | **Find Method** Returns the element that matches the given Condition 953 | 954 | ```js 955 | // FIND Method - returns only first element matchs the condition 956 | let finded = movements.find(mov => mov < 0); 957 | console.log(`First Withdrawal ${finded}`); 958 | ``` 959 | 960 | **FindIndex Method** Returns the element that matches the given Condition 961 | 962 | ```js 963 | // FindIndex Method - returns only first index that matchs the condition 964 | let index = movements.findIndex(mov => mov === 200); 965 | console.log(`First 200 Withdrawal was you ${index} transaction`); 966 | ``` 967 | 968 | **Some Method** Returns the true/false that when any element matches the given Condition 969 | 970 | ```js 971 | console.log(movements); // [200, 450, -400, 3000, -650, -130, 70, 1300] 972 | // Equality 973 | console.log(movements.includes(-130)); // true 974 | 975 | // Condition 976 | console.log(movements.some(mov => mov > 1500)); // true 977 | ``` 978 | 979 | **Every Method** Returns the true/false when all element matches the given Condition 980 | 981 | ```js 982 | // Every Method 983 | console.log(movements.every(mov => mov > 1500)); // false 984 | ``` 985 | 986 | **Reduce Method** 987 | Reduce boils("Reduces") all the array elements down to one single value (e.g. adding all the elements together) 988 | 989 | ```js 990 | // REDUCE method 991 | console.log(movements); 992 | const balance = movements.reduce((acc, cur, i, arr) => { 993 | console.log(`Iteration ${i}: Accumulator is ${acc}`); 994 | // acc :: accumulator value saved in acc 995 | // cur :: current number 996 | // i :: index 997 | // arr :: actuall arr 998 | /* Output ::: Iteration 0: Accumulator is 0 999 | Iteration 1: Accumulator is 200 1000 | ... 1001 | Iteration 7: Accumulator is 2540 1002 | */ 1003 | return acc + cur; 1004 | }, 0); 1005 | console.log(balance); // 3840 1006 | 1007 | // Finding Max Number 1008 | console.log(movements); // [ 200, 450, -400, 3000, -650, -130, 70, 1300 ] 1009 | const maxMov = movements.reduce( 1010 | (acc, cur) => (acc > cur ? acc : cur), 1011 | movement[0] 1012 | ); 1013 | console.log(maxMov); // 3000 1014 | ``` 1015 | 1016 | **Flat Method** Remve Nesting from Array 1017 | 1018 | ```js 1019 | const arr = [[1, 2, 3], [4, 5, 6], 7, 8, 9]; 1020 | console.log(arr.flat()); // [1, 2, 3, 4, 5, 6, 7, 8, 9] 1021 | 1022 | const arrDeep = [ 1023 | [1, 2, 3], 1024 | [4, 5, 6, [7, 8, 9, [0]]], 1025 | ]; 1026 | console.log(arrDeep.flat()); // [1, 2, 3, 4, 5, 6, Array(4)] 1027 | // Only flat till level 1 1028 | console.log(arrDeep.flat(2)); //[1, 2, 3, 4, 5, 6, 7, 8, 9, Array(1)] 1029 | console.log(arrDeep.flat(10)); //[1, 2, 3, 4, 5, 6, 7, 8, 9, 0] 1030 | ``` 1031 | 1032 | **Flatmap Method** Map Every element of array and then flat at the same time. Flat map only flat till level 1. 1033 | 1034 | ```js 1035 | const accc = [ 1036 | { 1037 | owner: 'Jonas Schmedtmann', 1038 | movements: [200, 450, -400, 3000, -650, -130, 70, 1300], 1039 | }, 1040 | { 1041 | owner: 'Jessica Davis', 1042 | movements: [5000, 3400, -150, -790, -3210, -1000, 8500, -30], 1043 | }, 1044 | { 1045 | owner: 'Steven Thomas Williams', 1046 | movements: [200, -200, 340, -300, -20, 50, 400, -460], 1047 | }, 1048 | { 1049 | owner: 'Sarah Smith', 1050 | movements: [430, 1000, 700, 50, 90], 1051 | }, 1052 | ]; 1053 | const balance = accc 1054 | .flatMap(acount => acount.movements) 1055 | .reduce((acc, val) => acc + val, 0); 1056 | console.log(balance); // 17840 1057 | ``` 1058 | 1059 | **Sorting the Array** 1060 | 1061 | ```js 1062 | const owners = ['Jonas', 'Zach', 'Chandraprakash', 'Charli']; 1063 | console.log(owners); // ['Jonas', 'Zach', 'Chandraprakash', 'Charli'] 1064 | 1065 | console.log(movements); //  [200, 450, -400, 3000, -650, -130, 70, 1300] 1066 | 1067 | movements.sort(); 1068 | 1069 | console.log(movements); // [-130, -400, -650, 1300, 200, 3000, 450, 70] 1070 | // Sort the numbers as they are strings not as number 1071 | 1072 | movements.sort((a, b) => (a > b ? 1 : -1)); 1073 | // if a > b then it will return 1 => means swap the numbers 1074 | // vice-versa b > a then return -1 => means not swap 1075 | console.log(movements); // [-650, -400, -130, 70, 200, 450, 1300, 3000] 1076 | 1077 | // to change accending to decending just change the condition or the return value 1078 | // you can give any value in place of -1 or 1 value should be positive or negative 1079 | 1080 | movements.sort((a, b) => b - a); 1081 | console.log(movements); //  [3000, 1300, 450, 200, 70, -130, -400, -650] 1082 | // Here b - a will be positive when b > a and positive value means swap the number and all will organize in decending order 1083 | ``` 1084 | 1085 | **More Ways of creating and Filling Array** 1086 | 1087 | ```js 1088 | // Filling items in array 1089 | //Creating array manually 1090 | const x = new Array(7); 1091 | console.log(x); // Array(7) [ <7 empty slots> ] 1092 | // Empty Array with 7 slot 1093 | 1094 | // On these array we can only use 1095 | x.fill(2); 1096 | console.log(x); // [ 2, 2, 2, 2, 2, 2, 2 ] 1097 | 1098 | // FILL method can be use on any array 1099 | x.fill(1, 3, 6); 1100 | console.log(x); // [ 2, 2, 2, 1, 1, 1, 2 ] 1101 | // Mutate the orignal array 1st param: what to fill 2nd params: from where to fill 3rd params: till what :: it will fill till end - 1 1102 | 1103 | // Araay.from 1104 | const y = Array.from({ length: 7 }, () => 1); 1105 | console.log(y); // [ 1, 1, 1, 1, 1, 1, 1 ] 1106 | 1107 | const z = Array.from({ length: 7 }, (_, i) => i + 1); 1108 | console.log(z); // [ 1, 2, 3, 4, 5, 6, 7 ] 1109 | 1110 | const movementUI = Array.from(document.querySelectorAll('.movements__value')); 1111 | console.log(movementUI); // Array(8) [ div.movements__value, .... , div.movements__value ] 1112 | 1113 | // MovementUI is Now array we can easily perform method like map or the reduce 1114 | console.log(movementUI.map(el => Number(el.textContent.replace('€', '')))); //[ 1300, 70, -130, -650, 3000, -400, 450, 200 ] 1115 | 1116 | // Second Arrgument in Array.from is mapping call back that you no need to map sepratly 1117 | const movementUI2 = Array.from( 1118 | document.querySelectorAll('.movements__value'), 1119 | el => Number(el.textContent.replace('€', '')) 1120 | ); 1121 | // directly got the array 1122 | console.log(movementUI2); // [ 1300, 70, -130, -650, 3000, -400, 450, 200 ] 1123 | ``` 1124 | 1125 | **Which Method When to Use** 1126 | 1127 | > What I Actually Want... 1128 | 1129 | 1. To Mutate original Array 1130 | 1131 | - Add to Original: 1132 | > .push (end) 1133 | > .unshift (start) 1134 | - Remove from Original 1135 | > .pop (end) 1136 | > .shift (start) 1137 | > .splice (any) 1138 | - Others 1139 | > .reverse 1140 | > .sort 1141 | > .fill 1142 | 1143 | 2. A new Array 1144 | 1145 | - Computed from Original 1146 | > .map (loop) 1147 | - Filteres using condition 1148 | > .filter 1149 | - Portion of Original 1150 | > .slice 1151 | - Adding original to other 1152 | > .concat 1153 | - Flattening the original 1154 | > .flat 1155 | >
1156 | > .flatMap 1157 | 1158 | 3. An Array index 1159 | 1160 | - Based on value: 1161 | > .indexOf 1162 | - Based on test condition: 1163 | > .findIndex 1164 | 1165 | 4. An array Element 1166 | - Based on test condition: 1167 | > .find 1168 | 5. Know if array includes 1169 | 1170 | - Based on value: 1171 | > .includes 1172 | - Based on test condition: 1173 | > .some 1174 | >
1175 | > .every 1176 | 1177 | 6. A new String 1178 | 1179 | - Based on separator string: 1180 | > .join 1181 | 1182 | 7. To transform to value 1183 | - Based on accumulator: 1184 | > .reduce (Boil down array to single .filter .findIndex .some (loop) value of any type: number, string, boolean, or even new array or object) 1185 | 8. To jusst loop array 1186 | - Based on callback: 1187 | > .forEach (Does not create a new array, just loops over it) 1188 | 1189 | ## Objects 1190 | 1191 | ```js 1192 | const chandraPrakash = { 1193 | firstName: 'ChandraPrakah', 1194 | lastName: 'Darji', 1195 | age: 2022 - 2002, 1196 | job: 'Student', 1197 | languages: ['JavaScript0', 'Python', 'Html', 'CSS'], 1198 | drivingLicense: false, 1199 | // can also hold a function beacuse function is a datatype 1200 | calcAge: function (birthYear) { 1201 | return 2022 - birthYear; 1202 | }, 1203 | calcAgeThis: function () { 1204 | return 2022 - this.birthYear; // Takes value from object 1205 | }, 1206 | getSummary: function () { 1207 | console.log( 1208 | `${this.firstName} is a ${ 1209 | this.job 1210 | } of ${this.calcAgeThis()} learnig today ${this.languages[0]} with ${ 1211 | this.drivingLicense ? 'a' : 'no' 1212 | } driving License` 1213 | ); 1214 | }, 1215 | }; 1216 | console.log(chandraPrakash); 1217 | 1218 | // Calling function 1219 | console.log(chandraPrakash.calcAge(2002)); 1220 | console.log(chandraPrakash.calcAgeThis()); 1221 | chandraPrakash.getSummary(); 1222 | 1223 | // Accesing Element 1224 | console.log(chandraPrakash.firstName); // Dot Notation 1225 | console.log(chandraPrakash['job']); // Bracket Notation 1226 | 1227 | // In Bracket Notation Expresion are Allowded 1228 | const nameKey = 'Name'; 1229 | console.log(chandraPrakash['first' + nameKey]); 1230 | console.log(chandraPrakash['last' + nameKey]); 1231 | 1232 | // Adding a Element in Objects 1233 | chandraPrakash.location = 'india'; 1234 | chandraPrakash['twitter'] = '@chandra_7852'; 1235 | 1236 | // Copying the Object 1237 | const jessica = { 1238 | firstName: 'Jessica', 1239 | lastName: 'Willams', 1240 | age: 27, 1241 | }; 1242 | const jessicaMarried = jessica; 1243 | console.log(jessica); // {firstName: 'Jessica', lastName: 'Willams', age: 27} 1244 | console.log(jessicaMarried); // {firstName: 'Jessica', lastName: 'Willams', age: 27} 1245 | jessicaMarried.lastName = 'Dave'; 1246 | console.log(jessica); // {firstName: 'Jessica', lastName: 'Dave', age: 27} 1247 | console.log(jessicaMarried); // {firstName: 'Jessica', lastName: 'Dave', age: 27} 1248 | // this will essentially just point to same object ... same object with diffrent names ... 1249 | const jessica2 = { 1250 | firstName: 'Jessica', 1251 | lastName: 'Willams', 1252 | age: 27, 1253 | family: ['Bob', 'Steven'], 1254 | }; 1255 | const jessica2Married = Object.assign({}, jessica2); 1256 | console.log(jessica2); // {firstName: 'Jessica', lastName: 'Willams', age: 27} 1257 | console.log(jessica2Married); // {firstName: 'Jessica', lastName: 'Willams', age: 27} 1258 | jessica2Married.lastName = 'Dave'; 1259 | console.log(jessica2); // {firstName: 'Jessica', lastName: 'Willams', age: 27} 1260 | console.log(jessica2Married); // {firstName: 'Jessica', lastName: 'Dave', age: 27} 1261 | // This will create new object by combining 2 Objects ... 1262 | 1263 | jessica2Married.family.push('Mary', 'John'); 1264 | console.log(jessica2); // {firstName: 'Jessica', lastName: 'Willams', age: 27, family: Array(4)} 1265 | console.log(jessica2Married); // {firstName: 'Jessica', lastName: 'Willams', age: 27, family: Array(4)} 1266 | // Object.assign only work for first level... in this Both object array is changed ... 1267 | // to copy prefectly you need to do deep clone 1268 | 1269 | // Destrucutring Object 1270 | const restaurant = { 1271 | name: 'Classico Italiano', 1272 | location: 'Via Angelo Tavanti 23, Firenze, Italy', 1273 | categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'], 1274 | starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'], 1275 | mainMenu: ['Pizza', 'Pasta', 'Risotto'], 1276 | 1277 | openingHours: { 1278 | thu: { 1279 | open: 12, 1280 | close: 22, 1281 | }, 1282 | fri: { 1283 | open: 11, 1284 | close: 23, 1285 | }, 1286 | sat: { 1287 | open: 0, // Open 24 hours 1288 | close: 24, 1289 | }, 1290 | }, 1291 | order: function (starterIndex, mainIndex) { 1292 | return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]]; 1293 | }, 1294 | orderDelivery: function ({ 1295 | starterIndex = 0, 1296 | mainIndex = 1, 1297 | time = '20:00', 1298 | address, 1299 | }) { 1300 | console.log( 1301 | `Order Recived! ${this.starterMenu[starterIndex]} and ${this.mainMenu[mainIndex]} will be delivered to ${address} at ${time}` 1302 | ); 1303 | }, 1304 | orderPasta: function (ing1, ing2, ing3) { 1305 | console.log( 1306 | `Here is Your delecious Pasta with ${ing1} , ${ing2} and ${ing3} ::: ` 1307 | ); 1308 | }, 1309 | }; 1310 | const { name, openingHours, categories } = restaurant; 1311 | console.log(name, openingHours, categories); // variable name should exactly same as in Object 1312 | const { 1313 | // Unpacking with diffrent variable Name 1314 | name: restaurantName, 1315 | openingHours: hours, 1316 | categories: tags, 1317 | breakMenu: menu = 'No Data', // default value if data no Exist 1318 | } = restaurant; 1319 | console.log(restaurantName, hours, tags, breakMenu); 1320 | 1321 | // Mutating variables 1322 | let a = 10, 1323 | b = 20; 1324 | const obj = { a: 42, b: 65, c: 86 }; 1325 | ({ a, b } = obj); 1326 | console.log(a, b); 1327 | 1328 | // Nested Objects 1329 | // Method 1 1330 | const { open: openFri, close: closeFri } = openingHours.fri; 1331 | console.log(openFri, closeFri); 1332 | // Method 2 1333 | const { 1334 | openingHours: { 1335 | fri: { open: o, close: c }, 1336 | }, 1337 | } = restaurant; 1338 | console.log(o, c); 1339 | 1340 | // Unpacking Use in Functions -> no More variable to specifiy as pparameter just one object -> then it will be unpacked 1341 | restaurant.orderDelivery({ 1342 | time: '22:30', 1343 | address: '402, Saheli Tailor', 1344 | mainIndex: 2, 1345 | starterIndex: 2, 1346 | }); 1347 | restaurant.orderDelivery({ 1348 | address: '402, Saheli Tailor', 1349 | }); 1350 | 1351 | // Spread Oprator in Object Use 1352 | const ingredient = [ 1353 | prompt("Let's make Pasta! Ingredient 1:"), 1354 | prompt('Ingredient 2:'), 1355 | prompt('Ingredient 3:'), 1356 | ]; 1357 | // Both will work 1358 | restaurant.orderPasta(ingredient[0], ingredient[1], ingredient[2]); 1359 | restaurant.orderPasta(...ingredient); 1360 | // Spread operator will work Better 1361 | 1362 | // ES2018 we can use ... spread opertor on Objects 1363 | const newRestaurant = { ...restaurant, founder: 'Gessiuf', founderYear: 1994 }; 1364 | console.log(newRestaurant); 1365 | 1366 | // Copying the Object 1367 | const restaurantCopy = { ...restaurant }; 1368 | restaurantCopy.name = 'Ristornos Roma'; 1369 | console.log(restaurantCopy); 1370 | 1371 | // Enhanced object litteral 1372 | const weekdays = ['mon', 'tue', 'wed', 'thu', 'sat', 'sun']; 1373 | 1374 | const openingHours = { 1375 | // property name can be modified now by expression 1376 | [weekdays[3]]: { 1377 | open: 12, 1378 | close: 22, 1379 | }, 1380 | [weekdays[4]]: { 1381 | open: 11, 1382 | close: 23, 1383 | }, 1384 | [weekdays[5]]: { 1385 | open: 0, 1386 | close: 24, 1387 | }, 1388 | [`day ${1 + 2 + 3}`]: { 1389 | open: 8, 1390 | close: 22, 1391 | }, 1392 | }; 1393 | const school = { 1394 | schoolName: 'Mark Socitey', 1395 | hours, // ES6 enhanced object literal 1396 | sorderPasta(ing1, ing2, ing3) { 1397 | // no need for function keyword and semi colon 1398 | console.log( 1399 | `Here is Your delecious Pasta with ${ing1} , ${ing2} and ${ing3} ::: ` 1400 | ); 1401 | }, 1402 | }; 1403 | console.log(school); 1404 | 1405 | // Without optional chaining 1406 | if (restaurant.openingHours && restaurant.openingHours.mon) 1407 | console.log(restaurant.openingHours.mon.open); 1408 | 1409 | console.log(restaurant.openingHours.mon.open); // with throw the error of Cannot read properties of undefined (reading 'open') 1410 | 1411 | // WITH Opetional Chaining 1412 | console.log(restaurant.openingHours.mon?.open); // here it wil check if restaurant.openingHours.mon it exist then and only the .openn will bw readed 1413 | 1414 | //////////////////////////////////// 1415 | // Without optional chaining 1416 | if (restaurant.openingHours && restaurant.openingHours.mon) 1417 | console.log(restaurant.openingHours.mon.open); 1418 | 1419 | console.log(restaurant.openingHours.mon.open); // with throw the error of Cannot read properties of undefined (reading 'open') 1420 | 1421 | // WITH Opetional Chaining 1422 | console.log(restaurant.openingHours.mon?.open); // here it wil check if restaurant.openingHours.mon it exist then and only the .openn will bw readed 1423 | console.log(restaurant.openingHours?.mon?.open); 1424 | */ 1425 | // Examples 1426 | const days = ['mon', 'tue', 'wed', 'thu', 'sat', 'sun']; 1427 | for (const day of days) { 1428 | const open = restaurant.openingHours?.[day]?.open ?? `closed`; 1429 | console.log(`On ${day} we open at ${open}`); 1430 | /* Output ::: On mon we open at closed 1431 | On tue we open at closed 1432 | On wed we open at closed 1433 | On thu we open at 12 1434 | On sat we open at 11 1435 | On sun we open at 0 1436 | */ 1437 | } 1438 | // Methods 1439 | console.log(restaurant.order?.(0, 1) ?? `Method does not exist`); // ['Focaccia', 'Pasta'] 1440 | console.log(restaurant.orderRissato?.(0, 1) ?? `Method does not exist`); 1441 | 1442 | 1443 | ////////////////////////////////////// 1444 | // Looping the Objects 1445 | // Display Keys only 1446 | const properties = Object.keys(openingHours); 1447 | console.log(properties); 1448 | 1449 | let openStr = `We are open o ${properties.length} days: `; 1450 | for (const day of properties){ 1451 | openStr+=`${day}, ` 1452 | } 1453 | console.log(openStr); 1454 | 1455 | // Property VALUES 1456 | const values = Object.values(openingHours) 1457 | console.log(values); 1458 | 1459 | // Entire Object 1460 | const entries = Object.entries(openingHours) 1461 | console.log(entries); 1462 | 1463 | for (const [day, {open,close}] of Object.entries(openingHours)){ 1464 | console.log(`On ${day} we open at ${open} and close at ${close}`); 1465 | } 1466 | ``` 1467 | 1468 | ## Sets 1469 | 1470 | ```js 1471 | const ordersSets = new Set([ 1472 | // To create Set 1473 | 'Pasta', 1474 | 'pizza', 1475 | 'Pizza', 1476 | 'Vada Pav', 1477 | 'Pizza', 1478 | 'Pasta', 1479 | ]); 1480 | console.log(ordersSets); 1481 | 1482 | console.log(new Set('ChandraPrakash')); // Can Pass Any Iterable 1483 | console.log(new Set('the quick brown fox jumps over a lazy dog')); 1484 | 1485 | console.log(ordersSets.size); // Size of Set 1486 | console.log(ordersSets.has('Pizza')); // Check for Element 1487 | ordersSets.add('Garlic Bread'); // Add an element 1488 | ordersSets.add('Garlic Bread'); 1489 | ordersSets.delete('Vada Pav'); // delete an elemnet 1490 | console.log(ordersSets); 1491 | 1492 | for (const order of ordersSets) console.log(order); // itreating to set through for-of loop 1493 | 1494 | ordersSets.clear(); // To clear the Set 1495 | console.log(ordersSets); 1496 | ``` 1497 | 1498 | ## Maps 1499 | 1500 | ```js 1501 | // Maps Fundamental 1502 | const rest = new Map(); // create a MAP 1503 | rest.set('name', 'Classico Italiano'); // Add a element 1504 | rest.set(1, 'Firenze, Italy'); 1505 | rest.set(2, 'Lisbon, Portugal'); 1506 | 1507 | rest.set('categories', ['Italian', 'Pizzeria', 'Vegetarian', 'Organic']) // Adding Mmultiple Element 1508 | .set('open', 11) 1509 | .set('close', 23) 1510 | .set(true, 'We are opeb :D') 1511 | .set(false, 'We are closed :('); 1512 | console.log(rest); 1513 | console.log(rest.get('name')); // Accesing the Element // Classico Italiano 1514 | console.log(rest.get(true)); // We are opeb :D 1515 | console.log(rest.get(1)); // Firenze, Italy 1516 | 1517 | const time = 21; 1518 | console.log(rest.get(time > rest.get('open') && time < rest.get('close'))); // We are opeb :D 1519 | 1520 | console.log(rest.has('categories')); // true 1521 | rest.delete(2); // delete an element 1522 | const arr = [1, 2, 3]; 1523 | rest.set(arr, 'Test'); // Arr should be a variable 1524 | console.log(rest.get(arr)); 1525 | console.log(rest); // test 1526 | // rest.clear() // clear the map 1527 | console.log(rest.size); // Size of the MAP 1528 | 1529 | // Itreation through Map 1530 | const question = new Map([ 1531 | ['question', 'What is the best programming languange in the world?'], 1532 | [1, 'C'], 1533 | [2, 'Java'], 1534 | [3, 'JavaScript'], 1535 | ['correct', 3], 1536 | [true, 'Correct 🎉'], 1537 | [false, 'Try again! 🤦'], 1538 | ]); 1539 | console.log(question); 1540 | 1541 | // Convert Object to Map 1542 | console.log(Object.entries(openingHours)); 1543 | const hoursMap = new Map(Object.entries(openingHours)); 1544 | console.log(hoursMap); 1545 | 1546 | // Quiz App 1547 | console.log(question.get('question')); 1548 | // Itreation 1549 | for (const [key, value] of question) { 1550 | if (typeof key === 'number') console.log(`Answer ${key}: ${value}`); 1551 | } 1552 | // const answer = Number(prompt("Enter Your Answer. 1 , 2 or 3")) 1553 | const answer = 3; 1554 | console.log(question.get(answer === question.get('correct'))); 1555 | 1556 | // Convert map to Arr 1557 | console.log([...question]); 1558 | console.log([...question.entries()]); 1559 | console.log([...question.keys()]); 1560 | console.log([...question.values()]); 1561 | ``` 1562 | 1563 | ## Working With String 1564 | 1565 | ```js 1566 | // Working With String 1567 | const airline = 'TAP Air Portugal'; 1568 | 1569 | // Accesing the character with indexing 1570 | console.log(airline[0]); // T 1571 | console.log(airline[1]); // A 1572 | console.log(airline[2]); // P 1573 | 1574 | // to infd the lenght of String 1575 | console.log(airline.length); // 16 1576 | 1577 | // To find the index of Character 1578 | console.log(airline.indexOf('r')); // 6 1579 | console.log(airline.lastIndexOf('r')); // 10 1580 | console.log(airline.indexOf('Portugal')); // 8 1581 | 1582 | // to Slice the charater 1583 | console.log(airline.slice(4)); // one Argument = start 1584 | console.log(airline.slice(0, 4)); // two argument = start,end 1585 | console.log(airline.slice(-8)); // Counting from ending 1586 | 1587 | // Sreing are also Objects that are converted to object when method is called 1588 | console.log(new String('Jonas')); 1589 | console.log(typeof new String('Jonas')); 1590 | 1591 | console.log(airline.toLowerCase()); // Lower casw 1592 | console.log(airline.toUpperCase()); // Upper case 1593 | 1594 | // Fixing Capitilaziation of name 1595 | const fixName = function (peopleName) { 1596 | return peopleName.toUpperCase()[0] + peopleName.toLowerCase().slice(1); 1597 | }; 1598 | console.log(fixName('ChaNDRAPrakASH')); 1599 | 1600 | // To Comparing user email 1601 | const email = 'hello@chandraprakash.com'; 1602 | const loginEmail = ' HeLLo@ChanDRApraKash.Com \n'; 1603 | 1604 | const proccesedEmail = loginEmail.toLowerCase().trim(); 1605 | console.log(proccesedEmail === email && 'Login Email is valid'); 1606 | console.log(proccesedEmail); 1607 | 1608 | // Replacing part of String 1609 | const priceGB = '288,56£'; 1610 | const priceUS = priceGB.replace('£', '$').replace(',', '.'); 1611 | console.log(priceUS); 1612 | 1613 | const announcment = 'All passenger come boarding door 23. Boarding door 23!'; 1614 | 1615 | console.log(announcment.replace('door', 'gate')); // Change only the first Occurence 1616 | // console.log(announcment.replaceAll('door', 'gate')); // Method gonna come in the Future 1617 | console.log(announcment.replace(/door/g, 'gate')); // Change with the Regular Expression to Change All Occurence 1618 | 1619 | // Bollean 1620 | const plane = 'Airbus A320neo'; 1621 | console.log(plane.includes('A320')); // true 1622 | console.log(plane.includes('blue')); // false 1623 | console.log(plane.startsWith('Air')); // true 1624 | 1625 | if (plane.startsWith('Airbus') && plane.endsWith('neo')) { 1626 | console.log('Part of NEW Airbus Family.🙂'); 1627 | } 1628 | 1629 | // Practise Exersise 1630 | const checkBaggage = function (items) { 1631 | items = items.toLowerCase(); 1632 | if (items.includes('gun') || items.includes('knife')) { 1633 | console.log('Your Not Allowed. 💥'); 1634 | } else { 1635 | console.log('You can Board. 🙂'); 1636 | } 1637 | }; 1638 | checkBaggage('I have a laptop, Some Food and a pocket Knife'); 1639 | checkBaggage('Socks and Camera'); 1640 | checkBaggage('Got some snacks and a gun for protection'); 1641 | 1642 | // Spliting the String 1643 | console.log('a+very+nice+string+by+made+with+plus+sign'.split('+')); // ['a', 'very', 'nice', 'string', 'by', 'made', 'with', 'plus', 'sign'] 1644 | 1645 | const [firstName, lastName] = 'Chandrprakash Darji'.split(' '); 1646 | const newName = ['Mr.', firstName, lastName.toUpperCase()].join(' '); // Mr. Chandrprakash DARJI 1647 | console.log(newName); 1648 | 1649 | const capitalizeName = function (name) { 1650 | name = name.split(' '); 1651 | name.forEach(nam => { 1652 | // name[name.indexOf(nam)] = nam[0].toUpperCase() + nam.slice(1).toLowerCase(); // Make to Parts and Capitalized 1653 | name[name.indexOf(nam)] = nam.replace(nam[0], nam[0].toUpperCase()); // replacing first Character ... 1654 | }); 1655 | console.log(name.join(' ')); 1656 | }; 1657 | capitalizeName('jessica ann smith davis'); 1658 | capitalizeName('chandrprakash darji'); 1659 | 1660 | // padding String 1661 | const message = 'Go to Gate no. 23'; 1662 | console.log(message.padStart(20, '+').padEnd(30, '+')); // +++Go to Gate no. 23++++++++++ 1663 | console.log('ChandrPrakash'.padStart(20, '+').padEnd(30, '+')); // +++++++ChandrPrakash++++++++++ 1664 | 1665 | // Exapmle 1666 | const maskCreditCard = function (number) { 1667 | const str = number + ''; 1668 | return str.slice(-4).padStart(str.length, '*'); 1669 | }; 1670 | console.log(maskCreditCard(6548736)); // ***8736 1671 | console.log(maskCreditCard(46557895613266)); // **********3266 1672 | console.log(maskCreditCard('4655789613264659876')); // ***************9876 1673 | 1674 | const badWaeatherMsg = 'Bad weather... All Ddepartues Delayed... '; 1675 | console.log(badWaeatherMsg.repeat(5)); // Bad weather... All Ddepartues Delayed... Bad weather... All Ddepartues Delayed... Bad weather... All Ddepartues Delayed... Bad weather... All Ddepartues Delayed... Bad weather... All Ddepartues Delayed... 1676 | 1677 | const planeInLine = function (n) { 1678 | console.log(`There are ${n} planes in line... ${'✈️'.repeat(n)}`); 1679 | }; 1680 | planeInLine(5); // There are 5 planes in line... ✈️✈️✈️✈️✈️ 1681 | planeInLine(12); // There are 12 planes in line... ✈️✈️✈️✈️✈️✈️✈️✈️✈️✈️✈️✈️ 1682 | planeInLine(2); // There are 2 planes in line... ✈️✈️ 1683 | 1684 | // Practise Question to Understand String Methods 1685 | const flights = 1686 | '_Delayed_Departure;fao93766109;txl2133758440;11:25+_Arrival;bru0943384722;fao93766109;11:45+_Delayed_Arrival;hel7439299980;fao93766109;12:05+_Departure;fao93766109;lis2323639855;12:30'; 1687 | 1688 | const getCode = str => str.slice(0, 3).toUpperCase(); 1689 | 1690 | flights.split('+').forEach(flightEntrie => { 1691 | let [status, fromPoint, toPoint, time] = flightEntrie.split(';'); 1692 | 1693 | const outPut = `${ 1694 | status.startsWith('_Delayed') ? '🔴' : '' 1695 | }${status.replaceAll('_', ' ')} from ${getCode(fromPoint)} to ${getCode( 1696 | toPoint 1697 | )} (${time.replace(':', 'h')})`.padStart(45); 1698 | console.log(outPut); 1699 | 1700 | /*Output --->> 🔴 Delayed Departure from FAO to TXL (11h25) 1701 | Arrival from BRU to FAO (11h45) 1702 | 🔴 Delayed Arrival from HEL to FAO (12h05) 1703 | Departure from FAO to LIS (12h30) 1704 | */ 1705 | }); 1706 | ``` 1707 | 1708 | ## Data Strucutres 1709 | 1710 | ### List of data Strucures 1711 | 1712 | - [Arrays](#arrays) 1713 | - [Objects](#objects) 1714 | - [Sets](#sets) 1715 | - [Maps](#maps) 1716 | 1717 | ### Sources of Data 1718 | 1719 | 1. **From the Program itself:** Data written directly in source code (e.g. status messages) 1720 | 2. **From the UI:** Data input from user or the data written in DOM (e.g. tasks in todo app) 1721 | 3. **From external sources:** Data fetched for example from web API (e.g. recipe objects) 1722 | 1723 | **->** Collection of data **->** Data Structures **->** 1. Simple List [ ARRAYS or SETS] && 2. Key/Value Pairs [OBJECTS or MAPS] (keys allow us to decribe values ) 1724 | 1725 | ### Usess of Arrays 1726 | 1727 | - ```js 1728 | const task = ['eat', 'code', 'sleep', 'repeat']; 1729 | ``` 1730 | 1731 | - Use when you need ordered list of values (might contain duplicates) 1732 | - Use when you need to manipulate data 1733 | 1734 | ### Usess of Sets 1735 | 1736 | - ```js 1737 | const = new Set(['eat', 'code', 'sleep', 'repeat']); 1738 | ``` 1739 | 1740 | - Use when you need to work with unique values 1741 | - Use when high-performance is really important 1742 | - Use to remove duplicates from arrays 1743 | 1744 | ### Usess of Object 1745 | 1746 | - ```js 1747 | const task = { 1748 | task: 'code', 1749 | date: 'today', 1750 | repeat: true, 1751 | }; 1752 | ``` 1753 | 1754 | - More “traditional” key/value store (“abused” objects) 1755 | - Easier to write and access values with . and [] 1756 | - Use when you simply need to map key to values 1757 | - Use when you need keys that are not strings 1758 | - Use when you need to include functions (methods) 1759 | - Use when working with JSON (can convert to map) 1760 | 1761 | ### Usess of Maps 1762 | 1763 | - ```js 1764 | const task = new Map([ 1765 | ['task', 'Code'], 1766 | ['date', 'today'], 1767 | [false, 'Start Coding'], 1768 | ]); 1769 | ``` 1770 | 1771 | - Better performance 1772 | - Keys can have any data type 1773 | - Easy to iterate 1774 | - Easy to compute size 1775 | - Use when you simply need to map key to values 1776 | - Use when you need keys that are not strings 1777 | 1778 | ### Basic Data Structures 1779 | 1780 | #### Numbers 1781 | 1782 | ```js 1783 | console.log(23 === 23.0); // true 1784 | // Real life Numbers are Base 10 // 0-9 1785 | // Js - Binary Base 2 // 0-1 1786 | 1787 | console.log(0.1 + 0.2); // 0.30000000000000004 1788 | console.log(0.1 + 0.2 === 0.3); // false 1789 | 1790 | // String to Number 1791 | console.log(Number('23')); 1792 | console.log(+'23'); 1793 | 1794 | // Parsing => Remove any Alpha But should start from number 1795 | console.log(Number.parseInt('30px')); // 30 1796 | console.log(Number.parseInt('e30px')); // NaN 1797 | 1798 | console.log(Number.parseInt('2.5rem')); // 2 1799 | console.log(Number.parseFloat('2.5rem')); // 2.5 1800 | 1801 | // Number is Global No need to Wright Number 1802 | console.log(parseInt('3rem')); // 3 1803 | 1804 | // Check if Value is Not a number => Value can be anything but NaN 1805 | console.log(Number.isNaN(20)); // false 1806 | console.log(Number.isNaN('20')); // false 1807 | console.log(Number.isNaN('20X')); // false 1808 | console.log(Number.isNaN(+'20X')); // true 1809 | console.log(Number.isNaN(20 / 0)); // false 1810 | 1811 | // Check if value is Number 1812 | console.log(Number.isFinite(20)); // true 1813 | console.log(Number.isFinite('20')); // false 1814 | console.log(Number.isFinite('20X')); // false 1815 | console.log(Number.isFinite(20 / 0)); // false 1816 | 1817 | //Check if Number is intergger or Not 1818 | console.log(Number.isInteger(20)); // true 1819 | console.log(Number.isInteger(20.0)); // true 1820 | console.log(Number.isInteger(20 / 0)); // false 1821 | 1822 | console.log(Math.sqrt(25)); // 5 Square Root 1823 | console.log(25 ** (1 / 2)); // 5 1824 | console.log(8 ** (1 / 3)); // 2 1825 | 1826 | // Max and Min Value 1827 | console.log(Math.max(3, 4, 12, 47, 54, 2, 23, 43, 55, 35, 45)); // 55 1828 | console.log(Math.max(3, 4, 12, 47, '54', 2, 23, 43, 55, 35, 45)); // 55 1829 | console.log(Math.max(3, 4, 12, 47, '54px', 2, 23, 43, 55, 35, 45)); // NaN 1830 | console.log(Math.min(3, 4, 12, 47, 54, 2, 23, 43, 55, 35, 45)); // 2 1831 | 1832 | console.log(Math.PI); // 3.141592653589793 1833 | 1834 | console.log(Math.trunc(Math.random() * 6) + 1); // any Number from 1 to 6 1835 | 1836 | const randomInt = (min, max) => 1837 | Math.floor(Math.random() * (max - min) + 1) + min; // generalized Function for random Number 1838 | 1839 | console.log(Math.trunc(34.343267)); // 34 removes value after deciaml point 1840 | 1841 | console.log(Math.round(25.3)); // 25 // round the Number 1842 | console.log(Math.round(25.9)); // 26 1843 | 1844 | console.log(Math.ceil(25.3)); // 26 // Round to UpSide 1845 | console.log(Math.ceil(25.9)); // 26 1846 | 1847 | console.log(Math.floor(25.3)); // 25 // Round to DownSide 1848 | console.log(Math.floor(25.9)); // 25 1849 | 1850 | console.log(Math.trunc(-25.9)); // -25 // removed after Point 1851 | console.log(Math.floor(-25.9)); // -26 // properly rounded 1852 | 1853 | // Rounding decimals ".toFixed" returns String not Number 1854 | console.log((2.7).toFixed(0)); // "3" 1855 | console.log((2.7).toFixed(3)); // "2.700" 1856 | console.log((2.734).toFixed(4)); // "2.7340" 1857 | console.log(+(2.743).toFixed(2)); // 2.74 1858 | 1859 | // Remainder 1860 | console.log(5 % 2); // 1 1861 | console.log(5 / 2); // 2 * 2 = 4 + 1 = 5 1862 | 1863 | // Check for Even=Odd 1864 | console.log(5 % 2 === 0); // false 1865 | console.log(4 % 2 === 0); // true 1866 | ``` 1867 | 1868 | #### BigInt 1869 | 1870 | ```js 1871 | // Largest Number In JS 1872 | // Total 64 bits are used to store number 1873 | // from 64 53 are used to store number other are used to store sign and decimal point of number 1874 | console.log(2 ** 53 - 1); // 9007199254740991 1875 | console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991 1876 | console.log(2 ** 53 + 1); // 9007199254740992 1877 | console.log(2 ** 53 + 2); // 9007199254740994 1878 | console.log(2 ** 53 + 3); // 9007199254740996 1879 | console.log(2 ** 53 + 4); // 9007199254740996 => Not Proper Result 1880 | // To create BigInt In JS for Larger Number => Just Put "n" beside it. You good to Go... 1881 | console.log(73657836895436789405789054864637665436728n); 1882 | console.log(BigInt(43234324)); // Function to create number 1883 | 1884 | // Operation 1885 | console.log(2000n + 1234n); // 3234n 1886 | console.log(3124235542353452345n * 43768342656784435n); // 136742611758230662608192758710250075n 1887 | 1888 | const huge = 1783124987173656782350871n; 1889 | const num = 29; 1890 | // console.log(huge * num); Not Posible :: You can't add normal and BigInt Number 1891 | console.log(huge * BigInt(num)); // 51710624628036046688175259n 1892 | 1893 | // Exception 1894 | // Math.sqrt(16n); :: No Math fun Can applicable 1895 | console.log(20n > 10); // true 1896 | console.log(20n > 30); // false 1897 | console.log(20n === 20); // false 1898 | console.log(typeof 20n); // bigint 1899 | console.log(20n === '20'); // false 1900 | 1901 | console.log(huge + ' is REALLY BIG !!!'); // 1783124987173656782350871 is REALLY BIG !!! script.js:400:9 1902 | 1903 | // Division 1904 | console.log(11n / 3n); // 3n => Removes number after decimal 1905 | console.log(11 / 3); // 3.6666666666666665 1906 | ``` 1907 | 1908 | #### Date 1909 | 1910 | ```js 1911 | // Create a Date 1912 | const now = new Date(); 1913 | console.log(now); // Date Fri Feb 25 2022 19:16:01 GMT+0530 (India Standard Time) 1914 | 1915 | console.log(new Date('Fri Feb 25 2022 19:15:50')); // Date Fri Feb 25 2022 19:15:50 GMT+0530 (India Standard Time) 1916 | console.log(new Date('DEcember 24, 2015')); // Date Thu Dec 24 2015 00:00:00 GMT+0530 (India Standard Time) 1917 | 1918 | console.log(new Date(account1.movementsDates[0])); // Date Fri Nov 01 2019 18:45:33 GMT+0530 (India Standard Time) 1919 | 1920 | console.log(new Date(2037, 10, 19, 15, 23, 5)); // Date Thu Nov 19 2037 15:23:05 GMT+0530 (India Standard Time) 1921 | console.log(new Date(2037, 10, 33)); // Date Tue Nov 19 2019 03:01:17 GMT+0530 (India Standard Time) 1922 | console.log(new Date(0)); // Unix Time // Date Thu Jan 01 1970 05:30:00 GMT+0530 (India Standard Time) 1923 | console.log(new Date(3 * 24 * 60 * 60 * 1000)); // 3 days after unix time // Date Sun Jan 04 1970 05:30:00 GMT+0530 (India Standard Time) 1924 | 1925 | const future = new Date(2037, 10, 19, 15, 23); 1926 | console.log(future); // Date Thu Nov 19 2037 15:23:00 GMT+0530 (India Standard Time) 1927 | console.log(future.getFullYear()); // 2037 -> full year 1928 | console.log(future.getMonth()); // 10 -> Month 0 based -> Jan - 0 1929 | console.log(future.getDate()); // 19 -> Date 1930 | console.log(future.getDay()); // 4 -> Day of the week 1931 | console.log(future.getHours()); // 15 1932 | console.log(future.getMinutes()); // 23 1933 | console.log(future.getSeconds()); // 0 1934 | 1935 | console.log(future.toISOString()); // -> 2037-11-19T09:53:00.000Z -> Universal time string 1936 | console.log(future.getTime()); // 2142237180000 -> milisecond passed till now 1937 | 1938 | console.log(new Date(2142237180000)); // milisecond to know the time 1939 | 1940 | console.log(Date.now()); // current time 1941 | 1942 | future.setFullYear(2040); // Set the new year 1943 | future.setMonth(12); 1944 | future.setDate(11); 1945 | future.setHours(2); 1946 | future.setMinutes(45); 1947 | future.setSeconds(0); 1948 | 1949 | console.log(future); // Fri Jan 11 2041 02:45:00 GMT+0530 (India Standard Time) 1950 | 1951 | // Operation On date 1952 | const future = new Date(2037, 10, 19, 15, 23); 1953 | console.log(+future); // 2142237180000 -> Total milisecond 1954 | 1955 | const calcDaysPassed = (date1, date2) => 1956 | Math.round(Math.abs(date1 - date2) / (1000 * 60 * 60 * 24)); 1957 | 1958 | const days1 = calcDaysPassed(new Date(2037, 10, 14), new Date(2037, 10, 20)); 1959 | console.log(days1); // 6 1960 | ``` 1961 | 1962 | #### Intl NameSpace 1963 | 1964 | Internationalization API - To convert your Data international like Dates, NUmbers, Plural Rules,etc Full read [MDN - Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl) 1965 | 1966 | ```js 1967 | const now = new Date(); 1968 | const locale = navigator.language; // "en-US" // Your Browser Language 1969 | console.log( 1970 | new Intl.DateTimeFormat(locale, { 1971 | timeStyle: 'short', 1972 | dateStyle: 'short', 1973 | }).format(now) 1974 | ); // 2/27/22, 2:47 PM 1975 | console.log( 1976 | new Intl.DateTimeFormat(locale, { 1977 | timeStyle: 'long', 1978 | dateStyle: 'long', 1979 | }).format(now) 1980 | ); // February 27, 2022 at 2:47:28 PM GMT+5:30 1981 | 1982 | const number = 123456.789; 1983 | console.log( 1984 | new Intl.NumberFormat('de-DE', { 1985 | style: 'currency', 1986 | currency: 'EUR', 1987 | }).format(number) 1988 | ); 1989 | // expected output: "123.456,79 €" 1990 | 1991 | // the Japanese yen doesn't use a minor unit 1992 | console.log( 1993 | new Intl.NumberFormat('ja-JP', { 1994 | style: 'currency', 1995 | currency: 'JPY', 1996 | }).format(number) 1997 | ); 1998 | // expected output: "¥123,457" 1999 | 2000 | // limit to three significant digits 2001 | console.log( 2002 | new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format( 2003 | number 2004 | ) 2005 | ); 2006 | // expected output: "1,23,000" 2007 | 2008 | let amount = 3500; 2009 | new Intl.NumberFormat('en-US', { style: 'decimal' }).format(amount); 2010 | // → '3,500' 2011 | new Intl.NumberFormat('en-US', { style: 'percent' }).format(amount); 2012 | // → '350,000%' 2013 | ``` 2014 | 2015 | ## Loops 2016 | 2017 | ### For Loops 2018 | 2019 | ```js 2020 | for (let rep = 0; rep <= 10; rep++) { 2021 | console.log(`Hello World ${rep}`); 2022 | } 2023 | /* output => Hello World 0 2024 | Hello World 1 2025 | Hello World 2 2026 | ... 2027 | ... 2028 | Hello World 10 */ 2029 | 2030 | // Looping through Array 2031 | const chandraPrakash = [ 2032 | 'ChandraPrakah', 2033 | 'Darji', 2034 | 2022 - 2002, 2035 | 'Student', 2036 | ['JavaScript', 'Python', 'Html', 'CSS'], 2037 | ]; 2038 | const type = []; 2039 | for (let index = 0; index < chandraPrakash.length; index++) { 2040 | // reading 2041 | console.log(chandraPrakash[index]); 2042 | // filling the array 2043 | type[index] = typeof chandraPrakash[index]; 2044 | } 2045 | 2046 | // Backword Loop 2047 | for (let index = chandraPrakash.length - 1; index >= 0; index--) { 2048 | console.log(chandraPrakash[index]); 2049 | } 2050 | /* output -> ['JavaScript', 'Python', 'Html', 'CSS'] 2051 | Student 2052 | 20 2053 | Darji 2054 | ChandraPrakah */ 2055 | ``` 2056 | 2057 | ### For of loops 2058 | 2059 | ```js 2060 | // for of loop [ Looping The ARRAYS ] 2061 | const menu = [...restaurant.starterMenu, ...restaurant.mainMenu]; 2062 | 2063 | for (const item of menu) console.log(item); // Take items one by one 2064 | 2065 | for (const item of menu.entries()) console.log(item); 2066 | /* Output ::: [0, 'Focaccia'] 2067 | [1, 'Bruschetta'] 2068 | [2, 'Garlic Bread'] 2069 | ... 2070 | */ 2071 | for (const [i, el] of menu.entries()) console.log(`${i}: ${el}`); 2072 | /* Output ::: 0: Focaccia 2073 | 1: Bruschetta 2074 | 2: Garlic Bread 2075 | ... 2076 | */ 2077 | 2078 | console.log(...menu.entries()); // [0, 'Focaccia'] [1, 'Bruschetta'] [2, 'Garlic Bread'] [3, 'Caprese Salad'] 2079 | // [4, 'Pizza'] [5, 'Pasta']0: 51: "Pasta"length: 2[[Prototype]]: Array(0) [6, 'Risotto'] 2080 | ``` 2081 | 2082 | ### ForEach loops 2083 | 2084 | In ForEach callback function the the first argument is the element and second on is index of that element, third argument in callBack is arr that is forEach loop is runned. 2085 | 2086 | ```js 2087 | // '---- 6. forEach Method ( ARRAY )----' 2088 | const movements = [200, 450, -400, 3000, -650, -130, 70, 1300]; 2089 | movements.forEach((movement, transferNo) => { 2090 | let type = movement > 0 ? 'Deposited' : 'Withdraw'; 2091 | console.log( 2092 | `You ${type} ${Math.abs( 2093 | movement 2094 | )}. Your Transaction Number is ${transferNo}` 2095 | ); 2096 | }); 2097 | 2098 | /* Output ::: You Deposited 200. Your Transaction Number is 0 2099 | You Deposited 450. Your Transaction Number is 1 2100 | You Withdraw 400. Your Transaction Number is 2 2101 | ... 2102 | */ 2103 | 2104 | // '---- 7. forEach Method ( MAP ) ----' 2105 | const currencies = new Map([ 2106 | ['USD', 'United States dollar'], 2107 | ['EUR', 'Euro'], 2108 | ['GBP', 'Pound sterling'], 2109 | ]); 2110 | currencies.forEach((value, key, map) => console.log(`${key}: ${value}`)); 2111 | /* Output ::: USD: United States dollar 2112 | EUR: Euro 2113 | GBP: Pound sterling 2114 | */ 2115 | 2116 | // '---- 8. forEach Method ( SET ) ----' 2117 | const currenciesUnque = new Set(['USD', 'GBP', 'USD', 'EUR', 'EUR']); 2118 | 2119 | currenciesUnque.forEach((value, _, set) => console.log(value)); 2120 | ``` 2121 | 2122 | ### Nested Loops 2123 | 2124 | ```js 2125 | for (let i = 0; i < 5; i++) { 2126 | console.log(`---------- Exersie Set No ${i} ----------`); 2127 | for (let j = 0; j < i; j++) { 2128 | console.log(`---- Exersie lift ${j}`); 2129 | } 2130 | } 2131 | ``` 2132 | 2133 | ### While loop 2134 | 2135 | ```js 2136 | // while loop -> Loop that doesn't require a counter 2137 | let rep = 1; 2138 | while (rep <= 3) { 2139 | console.log(`( ${rep} )is counter`); 2140 | rep++; 2141 | } 2142 | // Loop without Counter -> If we dont know how many time loop will run 2143 | let dice = Math.trunc(Math.random() * 6); 2144 | while (dice !== 6) { 2145 | console.log(dice); 2146 | dice = Math.trunc(Math.random() * 7); 2147 | if (dice === 6) console.log('Loops is about to end'); 2148 | } 2149 | ``` 2150 | 2151 | ### Loop Control Statments 2152 | 2153 | #### Continue 2154 | 2155 | ```js 2156 | // Continue -> When loop gets Continue the current itreation 2157 | // is stopped and skipped to next one ... 2158 | for (let index = 0; index < chandraPrakash.length; index++) { 2159 | if (typeof chandraPrakash[index] !== 'string') continue; 2160 | console.log(chandraPrakash[index]); 2161 | } 2162 | /* Output -> ChandraPrakah 2163 | Darji 2164 | Student*/ 2165 | ``` 2166 | 2167 | #### Break 2168 | 2169 | ```js 2170 | // Break -> When loop gets Break the whole is breaked 2171 | // and all itreation will not happen 2172 | for (let index = 0; index < chandraPrakash.length; index++) { 2173 | if (typeof chandraPrakash[index] === 'number') break; 2174 | console.log(chandraPrakash[index]); // no item will print if number is found 2175 | } 2176 | /* Output -> ChandraPrakah 2177 | Darji*/ 2178 | ``` 2179 | 2180 | ## Timers 2181 | 2182 | ### SetTimeout 2183 | 2184 | ```js 2185 | const ingredient = ['olives', 'spinach']; 2186 | // 1st argument 1 callback // 2nd time // 3rd argument for call back Fun() 2187 | const pizzaTower = setTimeout( 2188 | (ing1, ing2) => { 2189 | console.log(`Here is Pizza with ${ing1} and ${ing2} 🍕`); 2190 | }, 2191 | 3000, 2192 | ...ingredient 2193 | ); 2194 | console.log('Waiting...'); 2195 | // Clear the timeout at specific condition 2196 | if (ingredient.includes('spinach')) clearTimeout(pizzaTower); 2197 | ``` 2198 | 2199 | ### setInterval 2200 | 2201 | ```js 2202 | // Runs the call back fun() every given time 2203 | setInterval(() => { 2204 | console.log( 2205 | new Intl.DateTimeFormat('hi-IN', { timeStyle: 'long' }).format( 2206 | new Date() 2207 | ) 2208 | ); 2209 | }, 1000); 2210 | ``` 2211 | 2212 | ## DOM Manuplication 2213 | 2214 | **Document Object Model** Structured Representation Of Html Documents. Allows Javascript To Access Html Elements And Styles To Manipulate Them. 2215 | 2216 | DOM tree Structure 2217 | 2218 | ![Dom Tree](./Images/DOM_tree.png) 2219 | DOM is not Part of JavaScript ... 2220 | Javscript interact with DOM by WEB API's that browser Implements ... 2221 | 2222 | - [Accessing Dom Elements](#accessing-dom-elements) 2223 | - [Grab Children/Parent Node(s)](#grab-childrenparent-nodes) 2224 | - [Create New DOM Elements](#create-new-dom-elements) 2225 | - [Add Elements to the DOM](#add-elements-to-the-dom) 2226 | - [Remove Html Element](#remove-html-element) 2227 | - [Add/Remove/Toggle/Check Classes](#addremovetogglecheck-classes) 2228 | - [Updating Styles Using Dom](#updating-styles-using-dom) 2229 | - [Changing the Atributes](#changing-the-atributes) 2230 | 2231 | ### Accessing Dom Elements 2232 | 2233 | ```js 2234 | // Returns a reference to the element by its ID. 2235 | document.getElementById('someid'); 2236 | 2237 | // Returns an array-like object of all child elements which have all of the given class names. 2238 | document.getElementsByClassName('someclass'); 2239 | 2240 | // Returns an HTMLCollection of elements with the given tag name. 2241 | document.getElementsByTagName('LI'); 2242 | 2243 | // Returns the first element within the document that matches the specified group of selectors. 2244 | document.querySelector('.someclass'); 2245 | 2246 | // Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) 2247 | // that match the specified group of selectors. 2248 | document.querySelectorAll('div.note, div.alert'); 2249 | ``` 2250 | 2251 | ### Dom traversing 2252 | 2253 | ```javascript 2254 | const h1 = document.querySelector('h1'); 2255 | ``` 2256 | 2257 | Going DOWNWARDS : CHILD 2258 | 2259 | ```js 2260 | // return list of node with class ".highlight" 2261 | console.log(h1.querySelectorAll('.highlight')); 2262 | // reurns list of all the child node -> text,comment,element,etc. 2263 | console.log(h1.childNodes); 2264 | // returns the html collection of element 2265 | console.log(h1.children); 2266 | ``` 2267 | 2268 | Going UPWARADS : PARENT 2269 | 2270 | ```js 2271 | h1.closest('.header'); // returns the closet parent element -> can go as high it can go 2272 | 2273 | console.log(h1.parentNode); 2274 | console.log(h1.parentElement); 2275 | 2276 | // parentElement it is the same as parentNode. The only difference comes when a node's parentNode is not an element. If so, parentElement is null. 2277 | 2278 | document.body.parentNode; // the element 2279 | document.body.parentElement; // the element 2280 | 2281 | document.documentElement.parentNode; // the document node 2282 | document.documentElement.parentElement; // null 2283 | 2284 | document.documentElement.parentNode === document; // true 2285 | document.documentElement.parentElement === document; // false 2286 | ``` 2287 | 2288 | Since the `` element (document.documentElement) doesn't have a parent that is an element, parentElement is null. (There are other, more unlikely, cases where parentElement could be null, but you'll probably never come across them.) 2289 | [source StackOverflow](https://stackoverflow.com/questions/8685739/difference-between-dom-parentnode-and-parentelement) 2290 | 2291 | ```js 2292 | // Going SIDEWAY : Siblings 2293 | console.log(h1.previousElementSibling); // element before h1 2294 | console.log(h1.nextElementSibling); // element after 2295 | 2296 | console.log(h1.previousSibling); // previos node 2297 | console.log(h1.nextSibling); 2298 | 2299 | console.log(h1.parentElement.children); // all siblings 2300 | ``` 2301 | 2302 | ### Create New DOM Elements 2303 | 2304 | ```javascript 2305 | // create new elments 2306 | var newHeading = document.createElement('h1'); 2307 | var newParagraph = document.createElement('p'); 2308 | 2309 | // create text nodes for new elements 2310 | var h1Text = document.createTextNode('This is a nice header text!'); 2311 | var pText = document.createTextNode('This is a nice paragraph text!'); 2312 | 2313 | // attach new text nodes to new elements 2314 | newHeading.appendChild(h1Text); 2315 | newParagraph.appendChild(pText); 2316 | 2317 | // elements are now created and ready to be added to the DOM. 2318 | ``` 2319 | 2320 | ### Add Elements to the DOM 2321 | 2322 | ```javascript 2323 | // grab element on page you want to add stuff to 2324 | var firstHeading = document.getElementById('firstHeading'); 2325 | 2326 | // add both new elements to the page as children to the element we stored in firstHeading. 2327 | firstHeading.appendChild(newHeading); 2328 | firstHeading.appendChild(newParagraph); 2329 | 2330 | // can also insert before like so 2331 | 2332 | // get parent node of firstHeading 2333 | var parent = firstHeading.parentNode; 2334 | 2335 | // insert newHeading before FirstHeading 2336 | parent.insertBefore(newHeading, firstHeading); 2337 | 2338 | // directly add before and after 2339 | const header = document.querySelector('.header'); 2340 | header.after(message); 2341 | header.before(message); 2342 | ``` 2343 | 2344 | Suppose you have the following HTML: 2345 | 2346 | ```html 2347 |
2348 |

Some example text

2349 |
2350 |
2351 |

Some example text

2352 |
2353 | ``` 2354 | 2355 | You can insert another snippet of HTML between #box1 and #box2: 2356 | 2357 | ```javascript 2358 | var box2 = document.getElementById('box2'); 2359 | box2.insertAdjacentHTML('beforebegin', '

This gets inserted.

'); 2360 | 2361 | // beforebegin - The HTML would be placed immediately before the element, as a sibling. 2362 | // afterbegin - The HTML would be placed inside the element, before its first child. 2363 | // beforeend - The HTML would be placed inside the element, after its last child. 2364 | // afterend - The HTML would be placed immediately after the element, as a sibling. 2365 | ``` 2366 | 2367 | Add Multiple Element 2368 | 2369 | ```js 2370 | const header = document.querySelector('.header'); 2371 | const message = document.createElement('div'); 2372 | message.classList.add('cookie-message'); 2373 | message.innerHTML = 2374 | 'We use cookied for imporoved functionallity and analytics. '; 2375 | 2376 | header.prepend(message); // append as a first child 2377 | // header.append(message); // just change the place from first child to last child not gonna duplicate it again 2378 | header.append(message.cloneNode(true)); // .clonenode(true) give perms to duplicate the element 2379 | ``` 2380 | 2381 | ### Remove Html Element 2382 | 2383 | .remove to remove the element 2384 | 2385 | ```js 2386 | const message = document.createElement('div'); 2387 | document.querySelector('.btn--close-cookie').addEventListener('click', () => { 2388 | message.remove(); // easy Way 2389 | message.parentElement.removeChild(message); // Old way to remove 2390 | }); 2391 | ``` 2392 | 2393 | ### Add/Remove/Toggle/Check Classes 2394 | 2395 | ```javascript 2396 | // grab element on page you want to use 2397 | var firstHeading = document.getElementById('firstHeading'); 2398 | 2399 | // will remove foo if it is a class of firstHeading 2400 | firstHeading.classList.remove('foo'); 2401 | 2402 | // will add the class 'anotherClass' if one does not already exist 2403 | firstHeading.classList.add('anotherclass'); 2404 | 2405 | // add or remove multiple classes 2406 | firstHeading.classList.add('foo', 'bar'); 2407 | firstHeading.classList.remove('foo', 'bar'); 2408 | 2409 | // if visible class is set remove it, otherwise add it 2410 | firstHeading.classList.toggle('visible'); 2411 | 2412 | // will return true if it has class of 'foo' or false if it does not 2413 | firstHeading.classList.contains('foo'); 2414 | 2415 | // Don't use -> remove all classes and you can only add one class 2416 | logo.className = 'Chandraprakash'; 2417 | ``` 2418 | 2419 | ### Updating Styles Using Dom 2420 | 2421 | Change Any Style 2422 | 2423 | ```js 2424 | // To add styles .style.PROPERTY 2425 | message.style.backgroundColor = '#37383d'; 2426 | // Property name should be in Camel Case 2427 | message.style.width = '100%'; 2428 | ``` 2429 | 2430 | Access the property 2431 | 2432 | ```js 2433 | console.log(message.style.height); // You can't read any property. You can only read inline style 2434 | console.log(message.style.backgroundColor); // rgb(55, 56, 61) 2435 | 2436 | console.log(getComputedStyle(message)); // get the Object of styles 2437 | console.log(getComputedStyle(message).color); // To access specific style 2438 | // these values are computed by browser not necceserly decalared by developer 2439 | ``` 2440 | 2441 | Change the Property 2442 | 2443 | ```js 2444 | message.style.height = getComputedStyle(message).height + 48 + 'px'; // Not Gonna work beacuse compluted height will be in 40px you can't add with number so need to parse 2445 | message.style.height = 2446 | Number.parseFloat(getComputedStyle(message).height) + 40 + 'px'; 2447 | ``` 2448 | 2449 | Change CSS variable 2450 | 2451 | ```js 2452 | document.documentElement.style.setProperty('--color-primary', 'orangered'); 2453 | ``` 2454 | 2455 | ### Changing the Atributes 2456 | 2457 | Atributes - standard 2458 | 2459 | ```js 2460 | const logo = document.querySelector('.nav__logo'); 2461 | console.log(logo.alt); // Bankist logo 2462 | console.log(logo.className); // nav__logo 2463 | console.log(logo.src); // http://127.0.0.1:5500/img/logo.png // relative folder // for exact use get atribute 2464 | 2465 | // Changing Atributes 2466 | logo.alt = 'Befutiful minimlist Log'; 2467 | ``` 2468 | 2469 | Atributes - Non-Standard 2470 | 2471 | ```html 2472 | 2480 | ``` 2481 | 2482 | ```js 2483 | console.log(logo.designer); // undefined - Not gonna work 2484 | console.log(logo.getAttribute('designer')); // "Chandraprakash" 2485 | console.log(logo.getAttribute('src')); // img/logo.png 2486 | logo.setAttribute('company', 'Bankist'); 2487 | ``` 2488 | 2489 | Data Atributes 2490 | 2491 | ```js 2492 | console.log(logo.dataset.versionNumber); // 3.0 2493 | ``` 2494 | 2495 | ### Events in DOM 2496 | 2497 | Events are fired are Fired from user Interaction. These can arise from user interactions such as using a mouse or resizing a window, changes in the state of the underlying environment (e.g. low battery or media events from the operating system), and other causes. 2498 | 2499 | For Event List [MDN DOCS](https://developer.mozilla.org/en-US/docs/Web/Events) 2500 | 2501 | ```js 2502 | const h1 = document.querySelector('h1'); 2503 | const hero = document.querySelector('.header__img'); 2504 | 2505 | const h1MouseEnter = e => { 2506 | hero.style.transform = 'translateX(-40rem)'; 2507 | }; 2508 | // Simple Event listner 2509 | h1.addEventListener('mouseenter', h1MouseEnter); 2510 | 2511 | setTimeout(() => h1.removeEventListener('mouseenter', h1MouseEnter), 3000); // remvoves the event 2512 | 2513 | // old School way -> can't add multiple event listen on same activity 2514 | // can't remove event listner 2515 | h1.onmouseleave = e => { 2516 | hero.style.transform = 'translateX(0)'; 2517 | }; 2518 | ``` 2519 | 2520 | ## Short Circuiting 2521 | 2522 | ```js 2523 | // Short Circuting -> Use any data type, return ANY data type 2524 | console.log('---- ( OR ) ----'); // return true value or last Value 2525 | console.log(3 || 'Jonas'); 2526 | console.log('' || 'Jonas'); 2527 | console.log(true || 0); 2528 | console.log(undefined || null); 2529 | console.log(undefined || 0 || '' || 'hello' || 23 || null); 2530 | 2531 | // restaurant.numGuest = 23 2532 | const guests1 = restaurant.numGuest ? restaurant.numGuest : 10; 2533 | console.log(guests1); // restaurant.numGuest is not there so value will b2e 10 2534 | 2535 | const guest2 = restaurant.numGuest || 10; 2536 | console.log(guest2); // restaurant.numGuest is false value so 10 will be value 2537 | 2538 | console.log('---- ( AND ) ----'); // return the falsy Value or last Value 2539 | console.log(0 && 'Jonas'); // 0 2540 | console.log(7 && 'Jonas'); // Jonas 2541 | 2542 | console.log('Hello' && 23 && null && 'jonas'); // null 2543 | 2544 | // Practical Example 2545 | if (restaurant.orderPizza) { 2546 | restaurant.orderPizza('James', 'Spanich', 'cabbage'); // James ['Spanich', 'cabbage'] 2547 | } 2548 | 2549 | restaurant.orderPizza && restaurant.orderPizza('James', 'Spanich', 'cabbage'); // James ['Spanich', 'cabbage'] 2550 | ``` 2551 | 2552 | ## Nullish Coalescing Operator 2553 | 2554 | ```js 2555 | // Nullish Coalescing Operator 2556 | restaurant.numGuest = 0; 2557 | const guests = restaurant.numGuest || 10; 2558 | console.log(guests); 2559 | // Nullish: null and undefuned (NOT 0 and "") 2560 | const guestCorrect = restaurant.numGuest ?? 10; 2561 | console.log(guestCorrect); 2562 | ``` 2563 | 2564 | ## OOPS 2565 | 2566 | - 👉 Object-oriented programming (OOP) is a programming paradigm based on the concept of objects; 2567 | - 👉 We use objects to model (describe) real-world or abstract features; 2568 | - 👉 Objects may contain data (properties) and code (methods). By using objects, we pack data and the corresponding behavior into one block; 2569 | - 👉 In OOP, objects are self-contained pieces/blocks of code; 2570 | - 👉 Objects are building blocks of applications, and interact with one another; 2571 | - 👉 Interactions happen through a public interface (API): methods that the code outside of the object can access and use to communicate with the object; 2572 | - 👉 OOP was developed with the goal of organizing code, to make it more flexible and easier to maintain (avoid “spaghetti code”). 2573 | 2574 | ### Class 2575 | 2576 | Like a blueprint from which we can create new objects. 2577 | 2578 | Suppose there is Class of User that contain peoperties of user like username, password, email. 2579 | 2580 | You can use the class to create new user Object on yhe bases of the class without write every time same code and method for each user. That Object is know as Instance. You can create as many. 2581 | 2582 | ### THE 4 FUNDAMENTAL OOP PRINCIPLES 2583 | 2584 | #### Abstraction 2585 | 2586 | Ignoring or hiding details that don’t matter, allowing us to get an overview perspective of the thing we’re implementing, instead of messing with details that don’t really matter to our implementation. 2587 | 2588 | #### Encapsulation 2589 | 2590 | Keeping properties and methods private inside the class, so they are not accessible from outside the class. Some methods can be exposed as a public interface (API). 2591 | 2592 | #### Inheritance 2593 | 2594 | Making all properties and methods of a certain class available to a child class, forming a hierarchical relationship between classes. This allows us to reuse common logic and to model real-world relationships. 2595 | 2596 | #### Polymorphism 2597 | 2598 | A child class can overwrite a method it inherited from a parent class [it’s more complex that that, but enough for our purposes]. 2599 | 2600 | ### Prototypal inheritance 2601 | 2602 | - 👉 Objects are linked to a prototype object; 2603 | - 👉 Prototypal inheritance: The prototype contains methods (behavior) that are accessible to all objects linked to that prototype; 2604 | - 👉 Behavior is delegated to the linked prototype object 2605 | 2606 | ### 3 WAYS OF IMPLEMENTING PROTOTYPAL INHERITANCE IN JAVASCRIPT 2607 | 2608 | 1. Constructor functions 2609 | 2610 | - 👉 Technique to create objects from a function; 2611 | - 👉 This is how built-in objects like Arrays, Maps or Sets are actually implemented. 2612 | - [Constructor Function](#constructor-function) 2613 | 2614 | 2. ES6 Classes 2615 | 2616 | - 👉 Modern alternative to constructor function syntax; 2617 | - 👉 “Syntactic sugar”: behind the scenes, ES6 classes work exactly like constructor functions; 2618 | - 👉 ES6 classes do NOT behave like classes in “classical OOP” (last lecture). 2619 | - [ES2015 Classes](#es2015-classes) 2620 | 2621 | 1. Object.create() 2622 | 2623 | - 👉 The easiest and most straightforward way of linking an object to a prototype object. 2624 | 2625 | ### Constructor Function 2626 | 2627 | ```js 2628 | const Person = function (firstName, birthyear) { 2629 | // Instance property 2630 | this.firstName = firstName; 2631 | this.birthyear = birthyear; 2632 | 2633 | // Never do this for writing methods -> this gonna make function copy to all instance -> this will add multiple copies to all the Objects 2634 | // you can do prototype inherritence 2635 | // this.calcAge = function () { 2636 | // console.log(2037 - this.birthyear); 2637 | // }; 2638 | }; 2639 | 2640 | const Chandraprakash = new Person('Chandraprakash', 2002); 2641 | console.log(Chandraprakash); // Person {firstname: 'Chandraprakash', birthyear: 2002} 2642 | 2643 | // 1. New {} is Created 2644 | // 2. Function is called, this = {} 2645 | // 3. {} linked to prototype 2646 | // 4. Function actomatically returned {} 2647 | 2648 | const jonas = new Person('Jonas', 1991); 2649 | console.log(jonas); // Person {firstname: 'Jonas', birthyear: 1991} 2650 | 2651 | console.log(Chandraprakash instanceof Person); // true 2652 | ``` 2653 | 2654 | ### Prototypes 2655 | 2656 | ```js 2657 | Person.prototype.calcAge = function () { 2658 | console.log(2037 - this.birthyear); 2659 | }; 2660 | console.log(Person.prototype); // {calcAge: ƒ, constructor: ƒ} 2661 | 2662 | jonas.calcAge(); // 46 2663 | Chandraprakash.calcAge(); // 35 2664 | console.log(Chandraprakash); // Person {firstName: 'Chandraprakash', birthyear: 2002} 2665 | 2666 | console.log(jonas.__proto__ === Person.prototype); // true 2667 | // Person.prototype is not the prototype of person it is the prototype tha gonna used for object creted by that Constructre 2668 | 2669 | console.log(Person.prototype.isPrototypeOf(jonas)); //true 2670 | console.log(Person.prototype.isPrototypeOf(Chandraprakash)); // true 2671 | console.log(Person.prototype.isPrototypeOf(Person)); // false 2672 | // Person is not the prototype of Person it is only of Instance 2673 | 2674 | Person.prototype.species = 'Homo Sapiens'; 2675 | console.log(Chandraprakash.species); // Homo Sapiens 2676 | 2677 | console.log(jonas.hasOwnProperty('firstName')); // true -> Declared property is only its property 2678 | console.log(jonas.hasOwnProperty('species')); // false -> Inherited properties are not there actial property 2679 | ``` 2680 | 2681 | #### THE PROTOTYPE CHAIN 2682 | 2683 | ```js 2684 | const Person = function (firstName, birthyear) { 2685 | // Instance property 2686 | this.firstName = firstName; 2687 | this.birthyear = birthyear; 2688 | }; 2689 | Person.prototype.calcAge = function () { 2690 | console.log(2037 - this.birthyear); 2691 | }; 2692 | 2693 | Person.prototype.species = 'Homo Sapiens'; 2694 | console.log(ChandraPrakah.hasOwnProperty('species')); // false 2695 | ``` 2696 | 2697 | In Above code block we declare a small class named Person. 2698 | 2699 | In this class we had to Prototype properties `calcAge` and `species` only. 2700 | 2701 | `ChandraPrakah.hasOwnProperty('species')` 2702 | 2703 | In above line we just checking for does species name properties is there in Chandraprakash. 2704 | 2705 | It returns flase Because there is no such property of ChandraPrakash Object. 2706 | 2707 | You had noticed that we not have any such property name `.hasOwnProperty` in ChandraPrakash Object, then how it Works ? 2708 | 2709 | It Actually woks By the Prototype Chain, But What is this? 2710 | 2711 | In Prototype chain when JS engine not find any method in prototype then it checks the prototype of Object Class. 2712 | 2713 | Prototype is actually a Object having there own methods. 2714 | 2715 | It checks till the it prototype is null. 2716 | 2717 | let's Understand by the Code Block 2718 | 2719 | ```js 2720 | const h1 = document.querySelector('h1'); 2721 | console.dir(h1); 2722 | /* 2723 | { 2724 | accessKey: "" 2725 | align: "" 2726 | ... 2727 | ... 2728 | [[Prototype]]: HTMLHeadingElement 2729 | } 2730 | */ 2731 | ``` 2732 | 2733 | H1 element has prototype of HTMLHeadingElemt 2734 | Lets go deep 2735 | 2736 | ```js 2737 | console.dir(h1.__proto__); 2738 | /* 2739 | { 2740 | align: (...) 2741 | constructor: ƒ HTMLHeadingElement() 2742 | Symbol(Symbol.toStringTag): "HTMLHeadingElement" 2743 | ... 2744 | ... 2745 | [[Prototype]]: HTMLElement 2746 | } 2747 | */ 2748 | ``` 2749 | 2750 | Inside HTMLHeadingElemt there is constructor method and the end there is prototype of HTMLElement 2751 | 2752 | ```js 2753 | Lets dive more in 2754 | console.dir(h1.__proto__.__proto__); 2755 | /* 2756 | { 2757 | ... 2758 | ... 2759 | [[Prototype]]: Element 2760 | } 2761 | */ 2762 | ``` 2763 | 2764 | HTMLElement is consist of Element prototype 2765 | 2766 | This is Whole Prototype Chain of h1 Element 2767 | 2768 | > h1 > HTMLHeadingElement > HTMLElement > Element > Node > EventTarget > Object > null 2769 | 2770 | ### ES2015 Classes 2771 | 2772 | ```js 2773 | // 1. Class Expresion 2774 | const PersonClExp = class {}; 2775 | 2776 | // 2. Class Declartion 2777 | class Person { 2778 | constructor(firstName, birthyear) { 2779 | // Instance property 2780 | this.firstName = firstName; 2781 | this.birthyear = birthyear; 2782 | } 2783 | 2784 | // Method will added to .prototype property 2785 | calcAge = function () { 2786 | console.log(2037 - this.birthyear); 2787 | }; 2788 | 2789 | greet() { 2790 | console.log(`Hey ${this.firstName}`); 2791 | } 2792 | } 2793 | 2794 | const jessica = new Person('Jessica', 1996); 2795 | 2796 | // 1. Classes are not hoisted 2797 | // 2. Class are first-class citizen 2798 | // 3. Classes are executed in strict mode 2799 | ``` 2800 | 2801 | ### Getters and Setters 2802 | 2803 | > Getter and Setter for Objects 2804 | 2805 | ```js 2806 | const account = { 2807 | owner: 'Jonas', 2808 | movements: [23, 35, 46, 547, 687, 800, 43, 532, 34, 23], 2809 | 2810 | get latest() { 2811 | return this.movements.slice(-1).pop(); 2812 | }, 2813 | set newMov(mov) { 2814 | // Always need one argument 2815 | this.movements.push(mov); 2816 | }, 2817 | }; 2818 | 2819 | // Getter -> without calling the funtion get the value 2820 | console.log(account.latest); 2821 | 2822 | // Setter -> Using setter directly set the value 2823 | account.newMov = 3100; 2824 | console.log(account.movements); 2825 | ``` 2826 | 2827 | > Getter, Setter and Static method for Classes 2828 | 2829 | ```js 2830 | class Person { 2831 | constructor(fullName, birthyear) { 2832 | // Instance property 2833 | this.fullName = fullName; 2834 | this.birthyear = birthyear; 2835 | } 2836 | 2837 | // Method will added to .prototype property 2838 | calcAge() { 2839 | console.log(2037 - this.birthyear); 2840 | } 2841 | 2842 | greet() { 2843 | console.log(`Hey ${this.firstName}`); 2844 | } 2845 | 2846 | get age() { 2847 | return 2037 - this.birthyear; 2848 | } 2849 | // Set a property that already exist 2850 | set fullName(name) { 2851 | if (name.includes(' ')) this._fullName = name; 2852 | else console.log(`${name} is not full name`); 2853 | } 2854 | 2855 | get fullName() { 2856 | return this._fullName; 2857 | } 2858 | // Static Methods -> Not accesible by Object only Used on Person Constructor 2859 | static hey() { 2860 | console.log('Hey there 👋'); 2861 | console.log(this); 2862 | } 2863 | } 2864 | 2865 | const jessica = new Person('Jessic aDAv', 1996); 2866 | 2867 | console.log(jessica.fullName); 2868 | // console.log(jessica.age); // 41 2869 | 2870 | const walter = new Person('walter', 1332); 2871 | ``` 2872 | 2873 | ### Object.create() 2874 | 2875 | ```js 2876 | // First declared Object of prototype methods 2877 | const PersonProto = { 2878 | calceAge() { 2879 | console.log(2037 - this.birthYear); 2880 | }, 2881 | }; 2882 | // Then Creating the Empty Object 2883 | const steven = Object.create(PersonProto); 2884 | console.log(steven); // {} 2885 | // Adding Data 2886 | steven.name = 'Steven'; 2887 | steven.birthYear = 2002; 2888 | steven.calceAge(); // 35 2889 | console.log(steven); // {name: 'Steven', birthYear: 2002} 2890 | ``` 2891 | 2892 | ### InHertience between Classes 2893 | 2894 | 1. Using Function constructor 2895 | 2896 | ```js 2897 | // Person 2898 | const Person = function (firstName, birthyear) { 2899 | this.firstName = firstName; 2900 | this.birthyear = birthyear; 2901 | }; 2902 | 2903 | Person.prototype.calcAge = function () { 2904 | console.log(2037 - this.birthyear); 2905 | }; 2906 | 2907 | // Student 2908 | const Student = function (firstName, birthYear, course) { 2909 | Person.call(this, firstName, birthYear); // Calling the person class by giving the manually this keyword. 2910 | this.course = course; 2911 | }; 2912 | 2913 | // Linking Prototype of Person to student 2914 | Student.prototype = Object.create(Person.prototype); 2915 | // Set the constructor because the Object.create set it to perosn 2916 | Student.prototype.constructor = Student; 2917 | 2918 | Student.prototype.introduce = function () { 2919 | console.log(`My name is ${this.firstName} and I study ${this.course}`); 2920 | }; 2921 | 2922 | const mike = new Student('Mike', 2020, 'Computer Science'); 2923 | console.log(mike); 2924 | mike.introduce(); 2925 | mike.calcAge(); // No we Able to access method of Person 2926 | console.dir(Student.prototype.constructor); 2927 | ``` 2928 | 2929 | 2. Using ES2015 classes 2930 | 2931 | ```js 2932 | class Person { 2933 | constructor(firstName, birthyear) { 2934 | this.firstName = firstName; 2935 | this.birthyear = birthyear; 2936 | } 2937 | get age() { 2938 | return 2037 - this.birthyear; 2939 | } 2940 | } 2941 | 2942 | // extends directly connect child class with parent class 2943 | class Student extends Person { 2944 | constructor(firstName, birthyear, course) { 2945 | // Needs to Happen First 2946 | super(firstName, birthyear); 2947 | this.course = course; 2948 | } 2949 | introduce() { 2950 | console.log(`My name is ${this.firstName} and I study ${this.course}`); 2951 | } 2952 | // Overrided Parent method 2953 | get age() { 2954 | return 2022 - this.birthyear; 2955 | } 2956 | } 2957 | 2958 | const dave = new Student('jay Dave', 2003, 'Computer Science'); 2959 | console.log(dave); 2960 | dave.introduce(); 2961 | console.log(dave.age); 2962 | ``` 2963 | 2964 | ### Encapsulation 2965 | 2966 | Encapsulation is make methods and properties protected 2967 | 2968 | Below is Account class, It has some Properties and methods 2969 | 2970 | ```js 2971 | class Account { 2972 | constructor(owner, currency, pin) { 2973 | this.owner = owner; 2974 | this.currency = currency; 2975 | this.pin = pin; // this should not be accessible 2976 | this.movements = []; // this should not be accessible 2977 | this.locale = navigator.language; 2978 | 2979 | console.log(`Thanks ${this.owner} for Opening Account`); 2980 | } 2981 | // Public interface 2982 | deposit(amount) { 2983 | this.movements.push(amount); 2984 | } 2985 | withdraw(amount) { 2986 | this.deposit(-amount); 2987 | } 2988 | aproveLoan() { 2989 | return true; // this should not be accessible 2990 | } 2991 | requestLoad(amount) { 2992 | if (this.aproveLoan) { 2993 | this.deposit(amount); 2994 | console.log('Loan Approved'); 2995 | } 2996 | } 2997 | } 2998 | const acc1 = new Account('Chandraprakash', 'RUPEE', 111); 2999 | acc1.deposit(211); 3000 | acc1.withdraw(2211); 3001 | console.log(acc1); 3002 | console.log(acc1.pin); 3003 | ``` 3004 | 3005 | Anyone can access the `pin`, `movements` and `aproveLoan` method that can be harmful. 3006 | 3007 | lets do some encapsulation ---- 3008 | 3009 | 1. Protected But not Private 3010 | 3011 | ```diff 3012 | class Account { 3013 | .... 3014 | // Not truely private but Protected that you know not to mess with it. Still accesible 3015 | - this.pin = pin; 3016 | - this.movements = []; 3017 | + this._pin = pin; 3018 | + this._movements = []; 3019 | 3020 | - aproveLoan() { 3021 | + _aproveLoan() { 3022 | return true; 3023 | } 3024 | requestLoad(amount) { 3025 | - if (this.aproveLoan) { 3026 | + if (this._aproveLoan) { 3027 | this.deposit(amount); 3028 | console.log('Loan Approved'); 3029 | } 3030 | } 3031 | } 3032 | 3033 | ``` 3034 | 3035 | 2. Truely private classes 3036 | 3037 | These just a propasal to Implement not yet full in JS 3038 | 3039 | ```js 3040 | // Public Feild -> Anyone can access 3041 | // Private Feild -> Not accessible outside the Class 3042 | // Public Method -> Anyone can access 3043 | // Private Method -> Not implemented in any browser yet 3044 | 3045 | class Account { 3046 | // Public Feild -> Static Public proprities put outside of constructor 3047 | locale = navigator.language; 3048 | 3049 | // Private Field -> Add # before the properties name 3050 | #movements = []; 3051 | #pin; // -> the properties that are joing to assign by constructor then just declare it only 3052 | 3053 | constructor(owner, currency, pin) { 3054 | this.owner = owner; 3055 | this.currency = currency; 3056 | this.pin = pin; 3057 | console.log(`Thanks ${this.owner} for Opening Account`); 3058 | } 3059 | // Public Methods -> all method in constructor are Public 3060 | get movements() { 3061 | return this.#movements; 3062 | } 3063 | 3064 | deposit(amount) { 3065 | this.#movements.push(amount); 3066 | } 3067 | withdraw(amount) { 3068 | this.deposit(-amount); 3069 | } 3070 | 3071 | requestLoan(amount) { 3072 | if (this.#aproveLoan) { 3073 | this.deposit(amount); 3074 | console.log('Loan Approved'); 3075 | } 3076 | } 3077 | // Private Methods -> don't Use not used in any Browser yet 3078 | #aproveLoan() { 3079 | return true; 3080 | } 3081 | } 3082 | const acc1 = new Account('Chandraprakash', 'RUPEE', 111); 3083 | acc1.deposit(211); 3084 | acc1.withdraw(2211); 3085 | console.log(acc1); 3086 | console.log(acc1.requestLoan(300)); 3087 | console.log(acc1.#aproveLoan(300)); 3088 | // console.log(acc1.#pin); 3089 | // console.log(acc1.#movements); 3090 | // Error when you try to access 3091 | // Uncaught SyntaxError: Private field '#movements' must be declared in an enclosing class 3092 | ``` 3093 | 3094 | ### Chaining in Class methods 3095 | 3096 | Return the this at end of every method the you can easily perform any task on it by chainning 3097 | 3098 | ```js 3099 | class Account { 3100 | constructor(owner, currency, pin) { 3101 | this.owner = owner; 3102 | this.pin = pin; 3103 | this.currency = currency; 3104 | this.locale = navigator.language; 3105 | this.movements = []; 3106 | console.log(`Thanks ${this.owner} for Opening Account`); 3107 | } 3108 | movements() { 3109 | return this.movements; 3110 | } 3111 | deposit(amount) { 3112 | this.movements.push(amount); 3113 | return this; 3114 | } 3115 | withdraw(amount) { 3116 | return this.deposit(-amount); 3117 | } 3118 | aproveLoan() { 3119 | return true; 3120 | } 3121 | requestLoan(amount) { 3122 | if (this.aproveLoan) { 3123 | this.deposit(amount); 3124 | console.log('Loan Approved'); 3125 | } 3126 | return this; 3127 | } 3128 | } 3129 | const acc1 = new Account('Chandraprakash', 'RUPEE', 111); 3130 | // Chaining 3131 | acc1.deposit(300).deposit(200).withdraw(400).requestLoan(30).withdraw(4000); 3132 | console.log(acc1.movements); // [300, 200, -400, 30, -4000] 3133 | ``` 3134 | 3135 | ### Class in one Image 3136 | 3137 | ![Class in one Image](./Images/Class.png) 3138 | 3139 | > Image by [Jonas Schmedtmann](https://twitter.com/jonasschmedtman) 3140 | 3141 | ## SYNCHRONOUS CODE 3142 | 3143 | ```js 3144 | const p = document.querySelecter('.p'); 3145 | p.textContent = 'My name is Jonas!'; 3146 | alert('Text set!'); // Block the all code from running untill 3147 | // you close the popup 3148 | p.style.color = 'red'; 3149 | ``` 3150 | 3151 | - 👉 Most code is **synchronous**; 3152 | - 👉 Synchronous code is **executed line by line**; 3153 | - 👉 Each line of code **waits** for previous line to finish; 3154 | - 👎 _Long-running operations **block** code execution_. 3155 | 3156 | ## ASYNCHRONOUS CODE 3157 | 3158 | ```js 3159 | const p = document.querySelecter('.p'); 3160 | setTimeout(() => { 3161 | // ASYNCHRONOUS code NON-Blocking 3162 | p.textContent = 'My name is Jonas!'; 3163 | }, 5000); 3164 | p.style.color = 'red'; 3165 | ``` 3166 | 3167 | - 👉 Asynchronous code is executed **after a task that runs in the _“background”_ finishes**; 3168 | - 👍 Asynchronous code is **non-blocking**; 3169 | - 👉 Execution doesn’t wait for an **asynchronous** task to finish its work; 3170 | - 👉 Callback functions alone do **NOT** make code asynchronous! 3171 | 3172 | ## WHAT ARE AJAX CALLS? 3173 | 3174 | - **A**synchronous **J**avaScript **A**nd **X**ML: Allows us to communicate with remote web servers in an **asynchronous way**. With AJAX calls, we can **request data** from web servers dynamically. 3175 | 3176 | ## WHAT IS AN API? 3177 | 3178 | - 👉 Application Programming Interface: Piece of software that can be used by another piece of software, in order to allow applications to talk to each other; 3179 | 3180 | - 👉 There are be many types of APIs in web development: 3181 | 3182 | - DOM API - Geolocation API - Own Class API - “Online” API 3183 | 3184 | - 👉 “Online” API: Application running on a server, that receives requests for data, and sends data back as response; 3185 | 3186 | - 👉 We can build our own web APIs (requires back-end development, e.g. with node.js) or use 3rd-party APIs. 3187 | 3188 | ## WHAT HAPPENS WHEN WE ACCESS A WEB SERVER 3189 | 3190 | 1. Browser checks for DNS entry to find the corresponding IP address of website. 3191 | 2. The requests are sent using small data packets that contain information content of request and IP address it is destined for. 3192 | 3. Browser initiates a TCP (Transfer Control Protocol) connection with the server. 3193 | 4. Browser sends an HTTP request to the web server. GET or POST request. 3194 | 5. Server on the host computer handles that request and sends back a response. It assembles a response in some format like JSON, XML and HTML. 3195 | 6. Server sends out an HTTP response along with the status of response. 3196 | 3197 | ## WHAT ARE PROMISES? 3198 | 3199 | 👉 Promise: An object that is used as a placeholder for the future result of an asynchronous operation. 3200 | 👉 Promise: A container for an asynchronously delivered value. 3201 | 👉 Promise: A container for a future value. 3202 | 👉 We no longer need to rely on events and callbacks passed into asynchronous functions to handle asynchronous results; 3203 | 👉 Instead of nesting callbacks, we can chain promises for a sequence of asynchronous operations: escaping callback hell 🎉 3204 | 3205 | `XMLHttpRequest()` requries a event Listener and callback to load a respomse 3206 | 3207 | ```js 3208 | const country = 'india'; 3209 | const request = new XMLHttpRequest(); // Create a Request 3210 | request.open('GET', `https://restcountries.com/v2/name/${country}`); // Set the request server link 3211 | request.send(); // Sending the request 3212 | 3213 | request.addEventListener('load', function () { 3214 | // checking for request to load 3215 | const response = JSON.parse(this.responseText); 3216 | console.log(response); 3217 | }); 3218 | ``` 3219 | 3220 | Fetch API depends on promise 3221 | 3222 | ```js 3223 | const country = 'india'; 3224 | // request for data 3225 | fetch(`https://restcountries.com/v2/name/${country}`) 3226 | // after coming the request converted to json 3227 | .then(response => response.json()) 3228 | // After converted to json then renderCountry our Function is executed 3229 | .then(datts => renderCountry(datts)); 3230 | ``` 3231 | 3232 | ### Fetch API 3233 | 3234 | ```js 3235 | const getJSON = (url, errorMsg = 'Something went Wrong') => { 3236 | return fetch(url).then(response => { 3237 | if (!response.ok) throw new Error(`${errorMsg} (${response.status})`); // 3. if response is not ok then throw the error 3238 | // that will catch by the catch function at the End 3239 | return response.json(); // 4. for ok response it will convert to json and send it 3240 | }); 3241 | }; 3242 | 3243 | const getCountryData = country => { 3244 | btn.style.opacity = 0; 3245 | getJSON(`https://restcountries.com/v2/name/${country}`, 'Country not Found') // 2. getJson fun() will fetch the data 3246 | .then(datts => renderCountry(datts)) // 5. after getting the data renderCountry 3247 | // will run that will pprocess the data and display the country data 3248 | .catch(err => { 3249 | // 6. If any error encountered will these 3250 | // proceess it will display by the catch block 3251 | // throw are also deplayed here only 3252 | console.error(err, '🔥🔥🔥'); 3253 | // renderError just append the text to html 3254 | renderError(`Something went wrong 🔥 🔥 ${err.message}. Try again`); 3255 | }) 3256 | // 7. It will run no matter what status is ok or error 3257 | .finally(() => { 3258 | countriesContainer.style.opacity = 1; 3259 | }); 3260 | }; 3261 | 3262 | btn.addEventListener('click', () => getCountryData('usa')); 3263 | // 1. Data fetch gonna Start when btn is clicked 3264 | ``` 3265 | 3266 | Above code is for fetching the country data abd display on Screen. 3267 | 3268 | ### THE PROMISE LIFECYCLE 3269 | 3270 | 1. Pending - **Before** the future value is available 3271 | 2. Settled - **Asynchronous** task has **finished** 3272 | - FULFILLED - **Success**! The value is now **available** 3273 | - REJECTED - An **error** happened 3274 | 3275 | ### Building the Promise 3276 | 3277 | Simple lottery Promsie 3278 | 3279 | ```js 3280 | // Promise is Object -> new keyword is used to create it 3281 | const lotteryPromise = new Promise(function (resolve, reject) { 3282 | // resolve and reject are the function that gonna excuted on the conditionn 3283 | console.log('Lootery draw is happening 🔮'); 3284 | setTimeout(() => { 3285 | // condition for the Promise gonna resolve or not 3286 | if (Math.random() >= 0.5) { 3287 | // If condition is true then `You Win 💰` will be returned 3288 | resolve('You W in 💰'); 3289 | } else { 3290 | // Error will ne throw if Promise is rejected 3291 | reject(new Error('You Lost the Money 💩')); 3292 | } 3293 | }, 2000); 3294 | }); 3295 | 3296 | // Promise resolving 3297 | lotteryPromise.then(res => console.log(res)).catch(err => console.error(err)); 3298 | ``` 3299 | 3300 | Creating a fulfilled or rejected Promise 3301 | 3302 | ```js 3303 | Promise.resolve('ABC').catch(x => console.log(x)); 3304 | Promise.reject(new Error('Problem!')).catch(x => console.error(x)); 3305 | ``` 3306 | 3307 | ### Async Await Function 3308 | 3309 | ```js 3310 | const whereAmI = async function (country) { 3311 | // Method 1 3312 | fetch(`https://restcountries.com/v2/name/${country}`).then(response => 3313 | console.log(response) 3314 | ); 3315 | 3316 | // ES2017 Alternative async await function 3317 | const res = await fetch(`https://restcountries.com/v2/name/${country}`); 3318 | console.log(res); 3319 | }; 3320 | whereAmI('India'); 3321 | console.log('First'); 3322 | /* 3323 | First 3324 | Response {type: 'cors', url: 'https://restcountries.com/v2/name/India', redirected: false ... 3325 | */ 3326 | ``` 3327 | 3328 | ### Promise Combinator 3329 | 3330 | ```js 3331 | const getJSON = async (url, errorMsg = 'Something went Wrong') => { 3332 | const response = await fetch(url); 3333 | if (!response.ok) throw new Error(`${errorMsg} (${response.status})`); 3334 | return await response.json(); 3335 | }; 3336 | 3337 | // Promise Combinator 3338 | const get3Countries = async (c1, c2, c3) => { 3339 | try { 3340 | // When you fetch the data many times and sequence don't 3341 | // matter then you can use Promise.all to load in parellel 3342 | // and save the time 3343 | const data = await Promise.all([ 3344 | getJSON(`https://restcountries.com/v2/name/${c1}`), 3345 | getJSON(`https://restcountries.com/v2/name/${c2}`), 3346 | getJSON(`https://restcountries.com/v2/name/${c3}`), 3347 | ]); 3348 | console.log(data.map(d => d[0].name)); 3349 | } catch (error) { 3350 | console.error(error); 3351 | } 3352 | }; 3353 | get3Countries('India', 'usa', 'Russia'); 3354 | ``` 3355 | 3356 | ```js 3357 | /////////////////////////////////////// 3358 | // Other Promise Combinators: race, allSettled and any 3359 | // Promise.race 3360 | (async function () { 3361 | const res = await Promise.race([ 3362 | // the request that first fullfilled or rejected 3363 | getJSON(`https://restcountries.com/v2/name/italy`), 3364 | getJSON(`https://restcountries.com/v2/name/egypt`), 3365 | getJSON(`https://restcountries.com/v2/name/mexico`), 3366 | ]); 3367 | console.log(res[0]); 3368 | })(); 3369 | 3370 | const timeout = function (sec) { 3371 | return new Promise(function (_, reject) { 3372 | setTimeout(function () { 3373 | reject(new Error('Request took too long!')); 3374 | }, sec * 1000); 3375 | }); 3376 | }; 3377 | 3378 | Promise.race([ 3379 | // Race between timer of 4 sec and country api.. 3380 | // If request take more then 4 sec it will be rejected 3381 | getJSON(`https://restcountries.com/v2/name/tanzania`), 3382 | timeout(4), 3383 | ]) 3384 | .then(res => console.log(res[0])) 3385 | .catch(err => console.error(err)); 3386 | 3387 | // Promise.allSettled 3388 | Promise.allSettled([ 3389 | // When all Promise is settled either fullfilled or rejected 3390 | Promise.resolve('Success'), 3391 | Promise.reject('ERROR'), 3392 | Promise.resolve('Another success'), 3393 | ]).then(res => console.log(res)); 3394 | 3395 | Promise.all([ 3396 | // When all the request are fullfilled 3397 | Promise.resolve('Success'), 3398 | Promise.reject('ERROR'), 3399 | Promise.resolve('Another success'), 3400 | ]) 3401 | .then(res => console.log(res)) 3402 | .catch(err => console.error(err)); 3403 | 3404 | // Promise.any [ES2021] 3405 | Promise.any([ 3406 | // the any first request that get fullfilled 3407 | Promise.resolve('Success'), 3408 | Promise.reject('ERROR'), 3409 | Promise.resolve('Another success'), 3410 | ]) 3411 | .then(res => console.log(res)) 3412 | .catch(err => console.error(err)); 3413 | ``` 3414 | 3415 | ## AN OVERVIEW OF MODULES 3416 | 3417 | - 👉 Reusable piece of code that encapsulates implementation details; 3418 | - 👉 Usually a standalone file, but it doesn’t have to be. 3419 | 3420 | ### WHY MODULES? 3421 | 3422 | - 👉 Compose software: Modules are small building blocks that we put together to build complex applications; 3423 | - 👉 Isolate components: Modules can be developed in isolation without thinking about the entire codebase; 3424 | - 👉 Abstract code: Implement low-level code in modules and import these abstractions into other modules; 3425 | - 👉 Organized code: Modules naturally lead to a more organized codebase; 3426 | - 👉 Reuse code: Modules allow us to easily reuse the same code, even across multiple projects. 3427 | 3428 | ### NATIVE JAVASCRIPT (ES6) MODULES 3429 | 3430 | **ES6 MODULES** Modules stored in files, exactly one module per file. 3431 | 3432 | ||ES6 MODULE|SCRIPT| 3433 | |:---|:---:|:---:| 3434 | |👉 Top-level variables|Scoped to module |Global| 3435 | |👉 Default mode|Strict mode |“Sloppy” mode| 3436 | |👉 Top-level this|undefined| window| 3437 | |👉 Imports and exports|✅ YES| 🚫 NO| 3438 | |👉 HTML linking|`