├── .DS_Store ├── .github └── workflows │ └── notion.yml ├── LICENSE ├── README.md ├── array-methods ├── find.js ├── foreach.js ├── map.js ├── reduce1.js ├── reduce2.js └── reduce3.js ├── arrays ├── concat.js ├── includes.js ├── join-reverse.js ├── pop.js ├── shift.js ├── slice.js ├── sort.js └── splice.js ├── async-await ├── index.html └── script1.js ├── asynchronous-js ├── call-stack.js ├── callbackhell.js ├── index.html └── promises │ ├── chain.js │ ├── index.html │ ├── promise-value.js │ └── script.js ├── book.md ├── dom ├── app.css ├── app.js ├── create-elements.js ├── index.html ├── insert.js └── remove.js ├── functions ├── average.js ├── diceroll.js ├── funcargs.js ├── getcard.js ├── higherorder.js ├── makebetween.js ├── operations.js ├── pangram.js ├── passwordvalidator.js └── returnfunc.js ├── http-requests ├── axios │ ├── index.html │ ├── script.js │ └── script2.js ├── fetch │ ├── index.html │ └── script.js └── xml-http │ ├── index.html │ └── script.js ├── ifelse ├── prob1.js ├── prob2.js ├── prob3.js └── prob4.js ├── javascript-code ├── README.md ├── index.html └── storage.js ├── loops ├── gameboard.js └── numberguess.js ├── object-methods ├── anno.js ├── deckofcards.js └── thiskw.js └── oops ├── index.html └── script.js /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tush-tr/learn-lang-javascript/515acb7e3606aa34182a1150893784d12dc412f5/.DS_Store -------------------------------------------------------------------------------- /.github/workflows/notion.yml: -------------------------------------------------------------------------------- 1 | name: Notion2Github 2 | on: 3 | push: 4 | branches: 5 | - main 6 | jobs: 7 | auto-sync-from-notion-to-github: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - name: Checkout code 11 | uses: actions/checkout@v2 12 | 13 | - name: Notion2Github 14 | uses: younho9/notion2github@v1.1.0 15 | with: 16 | database-url: 'https://www.notion.so/1c29f6b165cc47579b243e7dab74f83d' 17 | docs-directory: ./ 18 | env: 19 | NOTION_TOKEN: ${{ secrets.NOTION_TOKEN }} 20 | 21 | 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Tushar Rajpoot 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JavaScript all concepts 2 | Amazing JavaScript learning and practice questions 3 | 4 | ### Content 5 |
  • Values and Variables- Premitive data types- Numbers 6 |
  • How JavaScript works? 7 |
  • Premitive data types- Boolean, Null, Undefined, String 8 |
  • Control and logic flow- if/else, switch, ternary operator, logical operators etc. 9 |
  • Arrays, array methods 10 |
  • Objects in JavaScript 11 |
  • Loops in JavaScript 12 |
  • Functions in JavaScript 13 |
  • Scope,Function expressions, Higher Order functions, callbacks, hoisting 14 |
  • Array callback methods- filter, forEach, reduce, map, some, every etc. 15 | 16 |
  • Default Parameters, Spreads,Rest Parameters, Destructuring 17 |
  • Object Methods and the "This" Keyword 18 |
  • Document Object Model 19 |
  • Communicating with Events 20 |
  • Asynchronous JavaScript, Callbacks and Promises 21 |
  • Making http requests: Fetch, Axios 22 |
  • Async and Await 23 |
  • Prototypes, Classes, & the new operator 24 |
  • JavaScript with Node.js 25 |

    26 | 27 | 28 |

    Values and variables

    29 | 30 | ## Primitive Data types 31 | every language out there has a group of types. 32 | Different categories for data. 33 |
  • Number - its a numeric value 34 |
  • String - text words, could be a number but inside quotation marks 35 |
  • Boolean - true or false values 36 |
  • Null 37 |
  • Undefined 38 |
  • technically there are two others- Symbol and BigInt 39 | 40 | ## Numbers in JS 41 | JS has one number type 42 |
  • positive numbers 43 |
  • negative numbers 44 |
  • whole number (integers) 45 |
  • Decimal Numbers(floats) 46 | 47 | > clear() - clears the console 48 | 49 | with numbers we have different mathematical operations that we can use kind of like a calculator. 50 | 51 | > Addition
    13+15 52 | 53 | > Substraction
    15-2 54 | 55 | > Multiply
    12*3 56 | 57 | > Divide
    12/6 58 | 59 | > Modulo
    12%4 - returns the remainder 60 | 61 | > // Comments after these two forward slashes 62 | 63 | 64 | #### exponent or exponential operator 65 | which looks like this two star star. 66 | > 4 ** 2 = 16 67 | 68 | ### NAN Not a Number 69 | NaN is a numeric value that represents something that is not a number. 70 | > 0/0 = NaN 71 | 72 | > 122 + NaN = NaN 73 | 74 | It doesn't necessarily mean something went wrong. 75 | 76 | 77 | ### Infinity 78 | which we can generate by doing something like 79 | 1 divided by zero javascript just has a way of representing a value of infinity. 80 | > 1/0 = infinity 81 | 82 |
    83 | 84 | 85 | # Variables 86 | 87 | Variables are like "labeled jars" for a value in JavaScript. 88 | 89 | We can store a value and give it a name, so that we can-- 90 | 91 |
  • Recall it 92 |
  • Use it 93 |
  • Or change it later on 94 | 95 | the basic syntax that we'll see first is using a keyword called let. 96 | ```javascript 97 | let age = 14; 98 | ``` 99 | Now there actually are two different ways that we can create variables in JavaScript at least two that 100 | are commonly used today. 101 | 102 | how to update a variable 103 | ```javascript 104 | age = age +1; 105 | ``` 106 | we should always keep our variable names in camel case like this 107 | ```js 108 | let ageOfTushar = 20; 109 | ``` 110 | ## Unary operators 111 | unary operators are operators where there's only one side. 112 | ```js 113 | let counter = 1; 114 | counter++; 115 | ``` 116 | 117 | ## Const 118 | const is just like let except we can't change the value. 119 | 120 | ## legacy of var 121 | before let and const , var was only way to declare the variables. Now there's no reason to use it. 122 | 123 | lets talk about other primitive data types- 124 |

    Booleans

    125 | booleans are simply true or false values. 126 | 127 | ```js 128 | let isFriend = true; 129 | isFriend = false; 130 | ``` 131 | 132 | -- in javascript we can change type of variables. 133 | if you have experience with any other programming language well maybe not any other but many other 134 | languages. 135 | When you declare a variable and you make it a number it needs to stay a number in JavaScript there is 136 | no restriction on that. 137 | We can change a number to a Boolean at any point. 138 | 139 | That's not saying it's a good idea at all. 140 | In fact it's one of the things a lot of people don't like about JavaScript and it's why things like 141 | TypeScript exist. 142 | 143 | # Strings 144 | strings are pieces of text, or strings of characters.We wrap them in quotes. 145 | 146 | ```js 147 | let rh = "This is going to be a good book"; 148 | "hi" + 1 149 | > "hi1" 150 | "hi" - 1 151 | >NaN 152 | ``` 153 | 154 | > Strings are indexed 155 | every character has a corresponding index. 156 | we can check length of a string using: 157 | ```js 158 | let s = "Tushar" 159 | let lengthOfs = s.length 160 | // accessing individual characters of a string using it's index 161 | console.log(s[0]) 162 | // access last character of a string 163 | console.log(s[s.length - 1]) 164 | // change characters 165 | s[1] = "u" 166 | // we can't change strings individual characters this way 167 | ``` 168 | > strings are immutable in javascript 169 | 170 | ## String methods 171 | strings come with a set of built in methods. which are actions that can be performed on or with that particular string. 172 | ```js 173 | thing.method() 174 | ``` 175 | 176 | ### toUpperCase() 177 | ```js 178 | let s = "tushar"; 179 | s.toUpperCase(); // returns new string with UPPER case 180 | ``` 181 | 182 | ### toLowerCase() 183 | ```js 184 | s.toLowerCase();// returns new string with all lowercase characters 185 | ``` 186 | 187 | ### trim() 188 | It just removes trailing leading and trailing whitespace so spaces at the beginning and 189 | end of a string when you call trim it returns a string where that space has been removed. 190 | ```js 191 | s.trim() 192 | ``` 193 | 194 | ## Methods with arguments 195 | some methods accepts arguments that modify their behaviour. 196 | ```js 197 | thing.method(args) 198 | ``` 199 | 200 | ### indexOf() 201 | tell you where in a string a given string occurs substring. 202 | 203 | ```js 204 | let st = "Tushar Rajpoot"; 205 | st.indexOf("u") // returns the index 206 | st.indexof("www") // return -1 not found 207 | ``` 208 | 209 | ### slice() 210 | takes index and gives sliced string 211 | ```js 212 | let s = "Tushar"; 213 | s.slice(0,3); 214 | >"Tus" 215 | ``` 216 | 217 | ### replace() 218 | returns a new string with replaced substring 219 | ```js 220 | let as = "I'm Tushar and I'm a programmer"; 221 | as.replace("programmer","developer") 222 | >"I'm Tushar and I'm a developer" 223 | ``` 224 | 225 | ## String espace characters 226 | 227 |
  • \n - newline 228 |
  • \' - single quote 229 |
  • \" - double quote 230 |
  • \\ - backslash 231 | 232 | ## String template literals 233 | template literals are strings that allow embedded expressions, which will be evaluated and then turned into a resulting string. 234 | 235 | use backtick for string template literals 236 | 237 | ```js 238 | let tu = 13; 239 | let s = `Number of tushar- ${tu}` 240 | ``` 241 | 242 | # Null and Undefined 243 | ### Null 244 | Intentional absence of any value.
    Must be assigned. 245 | 246 | ### Undefined 247 | Variables that don't have an assigned value are undefined. 248 | 249 | ```js 250 | let logg = null; 251 | ``` 252 | 253 | # Math object 254 | contains properties and methods for mathematical constantss and functions. 255 | 256 | ```js 257 | Math.PI // 3.14... 258 | 259 | //Rounding a number 260 | Math.round(4.9) // 5 261 | 262 | // Absolute value 263 | Math.abs(-456) // 456 264 | 265 | // Raises 2 to 5th power 266 | Math.pow(2,5) // 32 267 | 268 | // Removes decimal 269 | Math.floor(3.23) // 3 270 | ``` 271 | 272 | ## Random numbers 273 | Math.random() gives us a random decimal between 0 and 1 (non- inclusive) 274 | 275 | ```js 276 | Math.random() // it will return random decimal number between 0 and 1 277 | // 0.33493 278 | 279 | // genrate random number between 1 to 10 280 | const step1 = Math.random(); 281 | const step2 = step1 * 10; 282 | const step3 = Math.floor(step2); 283 | const step4 = step3 +1; 284 | 285 | // so basically we can do like this 286 | Math.floor(Math.random() * 10)+1; 287 | 288 | ``` 289 | 290 | ## TYPE OF 291 | we use type of to determine type of a given value. 292 | 293 | ```js 294 | let s = "tus"; 295 | typeof(s)// return string 296 | // we can use without these parentheses also 297 | typeof tu 298 | ``` 299 | 300 | # parseInt and parseFloat 301 | use to parse strings into numbers, but watch out for NaN. 302 | ```js 303 | let str = "123" 304 | parseInt(str) 305 | >123 306 | let s = "1.2" 307 | parseFloar(s); 308 | >1.2 309 | let st = "w1" 310 | parseInt(st); 311 | >NaN 312 | ``` 313 | 314 | 315 | 316 | 317 |

    How code is executed in JavaScript

    318 |

    Execution Context

    319 | Everything in JavaScript happens inside an execution context.
    320 | Assume it like a big box or container in which JS code is executed.
    321 | Execution context is a wrapper around your existing code; which contains code that you have not written, but is generated by JS engine. 322 |
    A JavaScript execution context is created each time when you run your JS code file. 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 |
    Memory ComponentCode Component
    Memory allocation of variablesCode execution
    334 | 335 |

    Components of execution context

    336 |
  • Memory Component
  • 337 | Memory component is a place where all the variables and keywords are stored as key value pairs. 338 | Ex: We have a variable called a equivalent to 10. 339 | 340 |
    const a = 10;
    341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 |
    Memory ComponentCode Component
    a:10Code execution
    353 | 354 |
  • Code Component
  • 355 | This is the place where code executed one line at a time. 356 | 357 |

    JavaScript is a synchronous single threaded language.

    358 |
  • Single Threaded
  • 359 | JavaScript can only execute one command at a time. 360 |
  • Synchronous Single threaded
  • 361 | JavaScript can only execute one command at a time and in a specific order. It can only go to the next line once the current line has been finished executing. 362 | 363 |

    What happens when you run your JS code

    364 |
      365 |
    1. When we run a JS program, An execution context will be created
    2. 366 | 375 |
    376 | 377 | Let's Assume we're executing below code 378 | 379 | ```JS 380 | var n = 2; 381 | function square(num){ 382 | var ans = num*num; 383 | return ans; 384 | } 385 | 386 | var square2 = square(n) 387 | var square3 = square(3) 388 | 389 | ``` 390 | 391 | So as we know first phase is creation- 392 |
    1. Memory Allocation Phase
    2. 393 | 397 | So when JS allocates memory what does it stores?
      398 | It stores a special value known as undefined. 399 |
      But in case of functions, it litterally stores the whole code of the function inside the memory space. 400 | 401 | 402 | 403 | 404 | 405 | 406 | 412 | 413 | 414 |
      Memory ComponentCode Component
      407 | n:undefined
      408 | square: {.....}
      409 | square2: undefined
      410 | square3: undefined
      411 |
      --------------------------
      415 |
    3. Code Execution Phase
    4. 416 | 434 |
    435 | 436 | 437 | 438 | 439 | 440 | 441 | 442 | 448 | 463 | 464 |
    Memory ComponentCode Component
    443 | n:2
    444 |
    445 | square2: 4
    446 | square3: 9
    447 |
    449 | 450 | 451 | 452 | 453 | 454 | 455 | 459 | 460 | 461 |
    Memory ComponentCode Component
    456 | num:2
    457 | ans:4
    458 |
    return ans
    462 |
    465 | 466 | 467 |


    468 | 469 |

    Controlling program logic and flow

    470 | 471 | ## Comparison Operators 472 | ```js 473 | > // greater than 474 | < // less than 475 | >= // greater than or equal to 476 | <= // less than or equal to 477 | == // equality 478 | != // not equal 479 | === // strict equality 480 | !== // strict non-equality 481 | // these give booleans true or false like this 482 | 5>2 // true 483 | 5<3 //false 484 | ``` 485 | 486 | ### double equals(==) 487 |
  • Checks for equality of value, but not equality of type. 488 |
  • It coerces both values to the same type and then compares them. 489 |
  • This can lead to some unexpected results. 490 | 491 | ### Triple equals(===) 492 |
  • Checks for equality of value and type. 493 | 494 | ```js 495 | 7 == '7' // true 496 | 7 ==='7' //false 497 | ``` 498 | 499 | > Always go with triple equals. 500 | 501 | ## Making decisions in the code 502 | A conditional statement can have three pieces- 503 |
  • If 504 |
  • Else if 505 |
  • Else 506 | 507 | ### If 508 | Run code if a given condition is true. 509 | ```js 510 | let rate = 3; 511 | if(rate===3){ 512 | console.log("Amazing"); 513 | } 514 | ``` 515 | 516 | ### Else If 517 | if not the first thing, maybe this another thing? 518 | ```js 519 | let rate = 2; 520 | if(rate===3){ 521 | console.log("Amazing"); 522 | } 523 | else if(rate === 2){ 524 | console.log("Oh its ok"); 525 | } 526 | ``` 527 | 528 | ### Else 529 | if nothing else was true, do this.. 530 | ```js 531 | let rate = 349; 532 | if(rate===3){ 533 | console.log("Amazing"); 534 | } 535 | else if(rate === 2){ 536 | console.log("Oh its ok"); 537 | } 538 | else{ 539 | console.log("Ok we don't know about it") 540 | } 541 | ``` 542 | 543 | ### Nesting 544 | we can nest conditionals inside conditionals 545 | ```js 546 | let password = "hello kiry"; 547 | if(password.length >=6){ 548 | if(password.indexOf(' ')!== -1){ 549 | console.log("Password can't include spaces"); 550 | } 551 | else{ 552 | console.log("Valid password") 553 | } 554 | } 555 | else{ 556 | console.log("password is too short"); 557 | } 558 | ``` 559 | 560 | ## Truthy and Falsy values 561 |
  • All values have an inherent truthy or falsy boolean value 562 |
  • Falsy values:--
    false
    0
    ""(empty string)
    null
    undefined
    NaN 563 |
  • Everything else is truthy/ 564 | 565 | ## Logical Operators 566 |
  • AND(&&) 567 |
  • OR(||) 568 |
  • NOT(!) 569 | 570 | ### AND(&&) 571 | Both sides must be true in order for the whole thing to be true 572 | 573 | ```js 574 | 1<=4 && 'a'==='a'; // true 575 | 9>10 && 9>=9 ; // false 576 | ``` 577 | 578 | ### OR(||) 579 | If one side is true, the whole thing is true 580 | 581 | ```js 582 | // only one side needs to be true 583 | 1!==1 || 10===10 // true 584 | ``` 585 | 586 | ### NOT(!) 587 | returns true if the expression is false 588 | 589 | ```js 590 | !null // true 591 | 592 | !(0===0) // false 593 | ``` 594 | 595 | ## Operator precedence 596 |
  • NOT(!) has higher precedence than && and ||. 597 |
  • && has higher precedence than ||.
    598 | 599 | ```js 600 | ! && || 601 | ``` 602 | we can alter these using parentheses. 603 | 604 | 605 | ## Switch Statement 606 | 607 | The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case, as well as statements in cases that follow the matching case. 608 | 609 | Syntax--- 610 | 611 | ```js 612 | switch (expression) { 613 | case value1: 614 | //Statements executed when the 615 | //result of expression matches value1 616 | [break;] 617 | case value2: 618 | //Statements executed when the 619 | //result of expression matches value2 620 | [break;] 621 | ... 622 | case valueN: 623 | //Statements executed when the 624 | //result of expression matches valueN 625 | [break;] 626 | [default: 627 | //Statements executed when none of 628 | //the values match the value of the expression 629 | [break;]] 630 | } 631 | ``` 632 | 633 | ## Ternary Operator 634 | 635 | ```javascript 636 | condition ? expIfTrue: expIfFalse 637 | ``` 638 | 639 | 640 | 641 | ## Some questions 642 |
      643 |
    1. Program to check if a number is even or odd.
    2. 644 |
    3. Program to find maximum, minimum among two numbers
    4. 645 |
    5. Program to find maximum, minimum among three numbers
    6. 646 |
    7. Program to check if an alphabet is a vowel or a consonant.
    8. 647 | 648 |
    649 | 650 |

    Arrays

    651 | 652 | Ordered collections of values 653 |
  • List of comments on IG post 654 |
  • Collection of levels in a game 655 |
  • Songs in a playlist

    656 | 657 | ### Creating arrays 658 | ```js 659 | // make an empty array 660 | let students = []; 661 | 662 | // array of strings 663 | let names = ["Rahul", "Tushar", "Sahul"]; 664 | 665 | // an array of numbers 666 | let rollNo = [23,45,2,34,6,7] 667 | 668 | // mixed array 669 | let stuff = [true, 435, 'tushar', null]; 670 | ``` 671 | 672 | #### Arrays are indexed 673 | ```js 674 | let colors = ['red','orange','yellow','green'] 675 | colors.length//4 676 | 677 | colors[0] // 'red' 678 | colors[1] // 'orange' 679 | colors[2] // 'yellow' 680 | colors[3] // 'green' 681 | colors[4] // 'undefined' 682 | ``` 683 | ### modifying arrays 684 | unlike strings, arrays are mutable, we can modify arrays 685 | 686 | ```js 687 | let shop = ['milk','sugar']; 688 | shop[1] = 'coffee'; 689 | // add something at the end 690 | shop[shop.length] = 'tomatos' 691 | ``` 692 | 693 | ## Array Methods 694 |
  • Push - add to end 695 |
  • Pop - remove from end 696 |
  • Shift remove from start 697 |
  • Unshift - add to start 698 |
  • ________________________________________ 699 |
  • concat - merge arrays 700 |
  • includes - look for a value, returns true or false 701 |
  • indexOf - just like str.indexOf 702 |
  • join - creates a string from arr 703 |
  • reverse - reverses an array 704 |
  • slice - copy portion of an arr 705 |
  • splice - remove/replace elements 706 |
  • sort - sorts an array. 707 | The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

    708 | 709 | >arrays are reference types which means that the actual array data is not the content that is stored in the slot in memory for each variable.Instead it is a reference. 710 | 711 | >we can modify array elements even it's initialized by const. 712 | 713 |

    Objects in JavaScript

    714 | 715 | An object allows us to store data where we can associate things in group pieces of data together but rather than simply ordering data based off of an index to zero with item the first the second like an array does. 716 | 717 |
  • Objects are collections of properties. 718 |
  • Properties are a key value pair. 719 |
  • Rather than accessing data using an index, we use custom keys. 720 | Property- key+ value 721 |
    722 | 723 | ```js 724 | const student = { 725 | name: "Tushar", 726 | rollno: 123, 727 | class: 12 728 | } 729 | ``` 730 | 731 | in other languages like Python objects are actually 732 | called dictionaries. 733 | 734 | ## Creating objects literals 735 | Instead of the square braces that we use for an array we use curly braces to signify an object. 736 | 737 | ```js 738 | // accessing properties 739 | student.name // accessing name 740 | ``` 741 | 742 | >when we create an object when we make a property the keys are automatically converted to strings. 743 | 744 | ```js 745 | let num ={ 746 | 34: "thirty four" 747 | } 748 | num.34 // throw error because it has converted to a string 749 | ``` 750 | 751 | ### Accessing objects properties 752 | ```js 753 | const colors ={ 754 | red: "#eb4d4b", 755 | yellow: "#f9ca24", 756 | blue: "#30336b" 757 | } 758 | colors.red 759 | colors['blue'] 760 | let cr = 'yellow'; 761 | colors[cr] 762 | 763 | const numbers = { 764 | 100: 'one hundred', 765 | 16: 'sixteen' 766 | '34 thing': "good" 767 | }; 768 | numbers[100] // 'one hundred' 769 | numbers['34 thing'] 770 | ``` 771 | 772 | ### Adding and updating properties 773 | 774 | ```js 775 | const users={} 776 | users['facebook'] = "Tushar"; 777 | users.insta = "tush_tr"; 778 | ``` 779 | 780 | ### Nested arrays and objects 781 | We can fill objects with keys that are arrays or also keys that are other objects. And we do this all the time because most of the data we work with in the real world is generally a combination of list or ordered data as well as key value pairs of data. 782 | 783 | ```js 784 | const shopCart = [ 785 | { 786 | product: 'milk', 787 | price: 12, 788 | quantity: 1 789 | }, 790 | { 791 | product: 'water bottle', 792 | price: 20, 793 | quantity: 5 794 | }, 795 | { 796 | product: 'coffee', 797 | price: 2, 798 | quantity: 20 799 | } 800 | ] 801 | 802 | const student = { 803 | firstName: 'Tushar', 804 | lastName: 'Rajpoot', 805 | hobbies: ['Music', 'reading'], 806 | marks:{ 807 | mid: 56, 808 | final: 94 809 | } 810 | } 811 | ``` 812 | 813 | We know that values in an array are not actually stored in a variable. The variable has limited space available to it. So it stores a reference sort of an address.
    814 | objects also work the exact same way. 815 | 816 | >we use const when we want the reference to stay the same like we always want to be pointing to this one object but the contents can come and go. 817 | 818 | #### Equality in arrays and objects 819 | the value of that variable has the little space in memory is not storing the array it's simply storing 820 | a reference to this array. 821 | ```js 822 | let n = [1,2,3]; 823 | let r = [1,2,3]; 824 | n==r // false 825 | n===r // false 826 | // so what we can do 827 | let newn = n; 828 | // now 829 | newn===n // true 830 | ``` 831 | if you're trying to compare arrays if you're trying to see if an array is equal to another array it's not as straightforward as you might hope it would be because a lot of times you're not trying to check if an array is the exact same array. 832 | 833 |

    Loops in JavaScript

    834 | Doing things repeatedly. 835 | 849 | 850 | ## For Loops 851 | 852 | ```js 853 | for( 854 | [initialExpression]; 855 | [condition]; 856 | [incrementExpression]; 857 | ){} 858 | // print hello 10 times-- 859 | for(let i=0;i<=10;i++){ 860 | console.log('hello'); 861 | } 862 | ``` 863 | 864 | #### print a multiplication table 865 | ```js 866 | const table = (num)=>{ 867 | for(let i=0;i<=10;i++){ 868 | console.log(`${num} X ${i} = ${num*i}`); 869 | } 870 | } 871 | table(4); 872 | ``` 873 | 874 | ### For loops and arrays 875 | we can use for loops to iterate over a string or an array. 876 |
    To loop over an array, start at 0 and continue to the last index(length-1). 877 | 878 | ```js 879 | const students = ['Ram','Shyam','Mohan']; 880 | for(let i=0;i=0;i--){ 886 | console.log(studentName[i]); 887 | } 888 | ``` 889 | 890 | ### Nested for loops 891 | we can nest loops 892 | ```js 893 | for(let i=0;i<=10;i++){ 894 | console.log("Outer loop",i); 895 | for(let j=10;j>=0;j--){ 896 | console.log("Inner loop",j); 897 | } 898 | } 899 | // we can use nested loops for iterating 2d arrays 900 | const gameBoard = [ 901 | [4,32,8,4], 902 | [64,8,32,2], 903 | [8,32,16,4], 904 | [2,8,4,2] 905 | ]; 906 | for(let i=0;i < gameBoard.length;i++){ 907 | // console.log(gameBoard[i]); 908 | for(let j=0;j ["South", "BollyWood", "Hollywood"] 988 | Object.values(movieRatings) 989 | // > [9.5, 2.5, 9.8] 990 | for(let x of Object.keys(movieRatings)){ 991 | console.log(x) 992 | } 993 | for(let ratings of Object.values(movieRatings)){ 994 | console.log(ratings); 995 | } 996 | ``` 997 | 998 | > We can loop over the keys of an object, using Object.key() and values using Object.values() 999 | 1000 | ## For In Loop 1001 | Loop over the keys in an object 1002 | ```js 1003 | for(variable in object){ 1004 | statement 1005 | } 1006 | // iterate over an object keys 1007 | const movieRatings ={South: 9.5, BollyWood: 2.5,Hollywood: 9.8}; 1008 | for(let movie in movieRatings){ 1009 | console.log(movie) 1010 | } 1011 | // accessing values with for in loop 1012 | for(let movie in movieRatings){ 1013 | console.log(movie) 1014 | console.log(movieRatings[movie]) 1015 | } 1016 | ``` 1017 | 1018 |

    Functions

    1019 | 1020 | Reusable procedures 1021 |
  • Functions allow us to write reusable, modular code. 1022 |
  • We define a 'chunk' of code that we can then execute at a later point. 1023 | 1024 | ### Defining functions 1025 | ```js 1026 | function funcName(){ 1027 | // do something 1028 | } 1029 | // let's write our first function 1030 | function hello(){ 1031 | console.log("Hello") 1032 | } 1033 | ``` 1034 | 1035 | ### function arguments 1036 | 1037 | we can also write functions that accept inputs, called arguments. 1038 | 1039 | ```js 1040 | function greet(person){ 1041 | console.log(`hello ${person}`) 1042 | } 1043 | function add(a,b){ 1044 | console.log(a+b); 1045 | } 1046 | ``` 1047 | 1048 | ### Return statement 1049 | built-in methods return values when we call them. We can store those values: 1050 | 1051 | ```js 1052 | function add(x,y){ 1053 | return x+y; 1054 | } 1055 | console.log(add(2,3)); 1056 | // we can capture a return value in a variable. 1057 | let a = add(2,3) 1058 | ``` 1059 | 1060 | #### No return 1061 | our functions print values out, but don't return anything. 1062 | ```js 1063 | function add(x,y){ 1064 | console.log(x+y) 1065 | } 1066 | add(3,3); 1067 | ``` 1068 | 1069 | 1070 | 1071 | 1072 | 1073 |

    Other Important concepts about functions

    1074 | 1075 | ### What is scope? 1076 | 1077 | > Variable "visibility" 1078 | 1079 |
  • The location where a variable is defined dictates where we have access to that variable. 1080 | 1081 | ### Function Scope 1082 | 1083 | ```js 1084 | function show(){ 1085 | let msg = "Hey I'm here"; 1086 | // msg is scoped to the show function 1087 | } 1088 | // we can't access or manipulate msg variable outside of this function. 1089 | ``` 1090 | 1091 | ### Block Scope 1092 | 1093 | ```js 1094 | let rad = 8; 1095 | if(rad>0){ 1096 | var a = 12; 1097 | const PI = 3.14; 1098 | let area = 2*PI*rad; 1099 | } 1100 | console.log(rad) // 8 1101 | console.log(area) // undefined 1102 | console.log(a) // 12 1103 | // this tells us that let and const have 1104 | // different scoping rules than var 1105 | // there was one more problem with var 1106 | let arr = [1,2,3,4]; 1107 | for(var i=0;i Functions are objects 1138 | We can put functions in an array.
    1139 | We can also put a function in an object. 1140 | 1141 | ### Functions as arguments 1142 | passing functions as an argument to another function or returning a function which is actually a very key part of javascript. 1143 |
    1144 | 1145 | #### What are higher order functions? 1146 | Functions that operate on/with other functions. They can: 1147 |
  • Accept other functions as arguments 1148 |
  • Return a function 1149 | 1150 | ```js 1151 | function callTwice(func){ 1152 | func(); 1153 | func(); 1154 | } 1155 | 1156 | function laugh(){ 1157 | console.log("hahahahahhah"); 1158 | } 1159 | 1160 | callTwice(laugh); 1161 | ``` 1162 | 1163 | ### Returning functions 1164 | ```js 1165 | function makeBetweenFunc(min,max){ 1166 | return function (val){ 1167 | return val>=min && val<=max; 1168 | } 1169 | } 1170 | const inAgeRange = makeBetweenFunc(18,100); 1171 | console.log(inAgeRange(45)) // true 1172 | ``` 1173 | 1174 | ## Callback Functions 1175 | A callback function is a function passed into another function as an argument, which is then invoked inside the outer function. 1176 | 1177 | ```js 1178 | function callTwice(func){ 1179 | func(); 1180 | func(); 1181 | } 1182 | function laugh(){ 1183 | console.log("hahahahha"); 1184 | } 1185 | callTwice(laugh) // pass a function as argument 1186 | // so here laugh is a callback function 1187 | // we can also do the same like this 1188 | callTwice(function (){ 1189 | console.log("Calling again"); 1190 | }) 1191 | ``` 1192 | 1193 | We can write our own function that accepts callbacks but also tons of the built in methods, that are really useful ones in JavaScript expect you to pass in a callback. 1194 | if you want to make a request to load data from Facebook API. That request takes time. We pass in a callback function that will be called when the request is finished. When the data is back if we want to run code when a user clicks on a button on a page or when they hover over a photo the code that we write to set that up requires us to pass in a callback function which will be executed when the user hovers or when the user clicks. 1195 | 1196 | #### Anonymous functions 1197 | we use anonymous functions when we call callback functions(higher order functions). We pass in an anonymous function rather than an existing function like laugh. 1198 | 1199 | There's nothing wrong with this 1200 | ```js 1201 | callTwice(laugh) 1202 | ``` 1203 | but sometimes we just need a one time use function. We don't need it to be a standalone function in which case we use an anonymous function. 1204 | 1205 | ### setTimeout function 1206 | There is a method called set timeout set timeout will run a certain block of code or a function of code after a certain number of milliseconds or seconds we pass in a number of milliseconds like five thousand which is five seconds but the first argument we need to pass it is a function so a function to run and then how long to wait before it runs. 1207 | 1208 | ```js 1209 | function notice(){ 1210 | alert("go away"); 1211 | } 1212 | setTimeout(notice,5000); 1213 | // this will wait till 5 second then execute notice function 1214 | // so we don't to define a function always we can use anonymous function like this 1215 | setTimeout(function(){ 1216 | alert("Go away"); 1217 | },5000); 1218 | ``` 1219 | 1220 | ## Hoisting 1221 | 1222 | >Hoisting is JavaScript's default behavior of moving declarations to the top. 1223 | 1224 | Remember that variables when we declare them but don't initialize them. For example var x and I don't give it a value, X is set to undefined. 1225 | ```js 1226 | let x; 1227 | >undefined 1228 | ``` 1229 | 1230 | so when you execute a js program, it hoists up all variable declaration. for ex, if you try to run this code 1231 | ```js 1232 | console.log(student); // undefined 1233 | var student = "Tushar" 1234 | ``` 1235 | When javascript is interpreting the code what happens is that it hoists up I'm doing air quotes but 1236 | you can't see it. It hoist up the variable declaration.(var student) 1237 | 1238 | #### With let and const- 1239 | Variables defined with let and const are hoisted to the top of the block, but not initialized. 1240 | Meaning: The block of code is aware of the variable, but it cannot be used until it has been declared. 1241 | 1242 | Using a let variable before it is declared will result in a ReferenceError. 1243 | 1244 | >when you declare variable with let it's not hoisted. 1245 | 1246 | 1247 | Using a const variable before it is declared, is a syntax errror, so the code will simply not run. 1248 | 1249 | > Let and const are not hoisted 1250 | 1251 | #### Functions are hoisted 1252 | ```js 1253 | show(); 1254 | function show(){ 1255 | console.log("helooooo"); 1256 | } 1257 | ``` 1258 | 1259 | But But if we use function expression, it not gonna work 1260 | ```js 1261 | console.log(show) // undefined because its a variable that has been declared 1262 | show(); // error 1263 | var show = function(){ 1264 | console.log("Hloooo") 1265 | } 1266 | // but if we declare this function using let or const it will not work. 1267 | ``` 1268 | 1269 |

    Array callback methods

    1270 | 1271 |
  • Arrays come with many built-in methods that accept callback functions. 1272 | 1273 | ## For Each 1274 | accepts a callback function. 1275 | Calls the function once per element in the array. 1276 | 1277 | ```js 1278 | const num = [1,2,3,4,5,6]; 1279 | num.forEach(function(n){ // n parameter represents one element at a time 1280 | console.log(n) 1281 | }) 1282 | ``` 1283 | We can also add a second parameter to our callback to the function here if we want to use the index. 1284 | ```js 1285 | num.forEach(function(e,i){ 1286 | console.log(i,e); 1287 | }) 1288 | ``` 1289 | 1290 | ## Map Method 1291 | creates a new array with the results of calling a callback on every element in the array 1292 | 1293 | ```js 1294 | const texts = ['fer','rrer','rer','erre']; 1295 | const caps = texts.map(function(t){ 1296 | return t.toUpperCase(); 1297 | }) 1298 | ``` 1299 | 1300 | ## Arrow Functions 1301 | Syntactically compact alternative to a regular function expression. 1302 | ```js 1303 | const square = (x)=>{ 1304 | return x*x; 1305 | } 1306 | ``` 1307 | 1308 | ### Implicit return 1309 | all these functions do the same thing: 1310 | ```js 1311 | const isEven = function(num){ 1312 | return num%2===0; 1313 | } 1314 | const isEven = (num)=>{ 1315 | return num%2===0; 1316 | } 1317 | const isEven = num =>{ 1318 | return num%2===0; 1319 | } 1320 | const isEven = num =>{ // implicit return 1321 | num%2===0 1322 | } 1323 | const isEven = num=> num%2===0;// one-liner implicit return 1324 | ``` 1325 | 1326 | ## Find method 1327 | returns the value of the first element in the array that satisfies the provided testing function. 1328 | 1329 | ```js 1330 | let shoppingList = [ 1331 | "Veggies", 1332 | "Milk", 1333 | "Notebooks" 1334 | ] 1335 | let item = shoppingList.find(item=>{ 1336 | return item.includes("Milk"); 1337 | }) 1338 | ``` 1339 | 1340 | ## Filter method 1341 | creates a new array with all elements that pass the test implemented by the provided function. 1342 | ```js 1343 | const numbers = [12,334,542,3,34,54,5,45,3,4,523,6,3] 1344 | const evens = numbers.filter(n=>{ 1345 | return n%2===0; 1346 | }) 1347 | ``` 1348 | 1349 | ## Every and Some method 1350 | #### Every- 1351 | tests whether all elements in the array pass the provided function It returns a boolean value. 1352 | ```js 1353 | const words = ['dog','dog','dig','dag','bag']; 1354 | words.every(word=>{ 1355 | return word.length === 3; 1356 | }) // true 1357 | ``` 1358 | 1359 | #### Some - 1360 | Similar to every, but returns true if any of the array elements pass the test function. 1361 | ```js 1362 | words.some(word=>{ 1363 | return word.length >4; 1364 | }) 1365 | ``` 1366 | 1367 | ## Sort 1368 |
    1369 | arr.sort(compareFunc(a,b)))
    1370 | 
    1371 |
  • If compareFunc(a,b) returns less than 0 1372 | -> Sort a before b 1373 |
  • If compareFunc(a,b) returns 0 1374 | -> leave a and b unchanged with respect to each other 1375 |
  • If compareFunc(a,b) returns greater than 0 1376 | -> Sort b before a 1377 | 1378 | 1379 | 1380 | ```js 1381 | const prices = [122,4542,453,5248,78709,3435]; 1382 | prices.sort(); // it's weird converts into strings then sort 1383 | 1384 | prices.sort((a,b)=> a-b); 1385 | 1386 | prices.sort((a,b)=>b-a); 1387 | 1388 | ``` 1389 | 1390 | ## Reduce Method 1391 | executes a reducer function on each element of the array, resulting in a single value. 1392 | 1393 | #### Summing an array 1394 | ```js 1395 | const arr = [3,5,7,9,11]; 1396 | arr.reduce((accumulator, currentValue)=>{ 1397 | return accumulator+currentValue; 1398 | }) 1399 | ``` 1400 | 1401 | 1402 | 1403 | 1404 | 1405 | 1406 | 1407 | 1408 | 1409 | 1410 | 1411 | 1412 | 1413 | 1414 | 1415 | 1416 | 1417 | 1418 | 1419 | 1420 | 1421 | 1422 | 1423 | 1424 | 1425 | 1426 | 1427 | 1428 | 1429 | 1430 | 1431 | 1432 |
    CallbackAccumulatorCurrentvaluereturn value
    first call358
    second call8715
    third call15924
    fourth call241135
    1433 | 1434 | 1435 | it's not always about summing or multiplying or accumulating data in one number. It could be finding the maximum value in an entire array. 1436 | 1437 | #### Initial value 1438 | when you use reduce you can actually pass in an initial starting value. So after your callback the format would be something dot reduce. 1439 | ```js 1440 | [12,23,5,6].reduce((acc,curr)=>{ 1441 | return acc+curr; 1442 | },100) 1443 | ``` 1444 | 1445 | #### Tallying 1446 | we can tally up results from an array we can group different values in an array using an object. 1447 | ```js 1448 | const vote = ['y','y','n','y','y','y','n'] 1449 | const tally = vote.reduce((tally, vote)=>{ 1450 | tally[vote] = (tally[vote] || 0)+1 1451 | return tally; 1452 | },{}) 1453 | // {}- initial object 1454 | ``` 1455 |

    Default Parameters, Spreads,Rest Parameters, Destructuring

    1456 | 1457 | list of some important JS new features 1458 | 1459 | 1460 | 1461 | 1462 | 1463 | 1464 | 1465 | 1466 | 1467 | 1468 | 1469 | 1470 | 1471 | 1472 | 1473 | 1474 | 1475 | 1476 | 1477 | 1478 | 1479 | 1480 | 1481 | 1482 | 1483 |
    Arrow functionsString template literalsLet and const
    For...offor...inExponent operator
    String.includes()Array.includes()Object.values()
    Rest & SpreadDestructuringDefault function params
    Object EnhancementsClassesAsync Functions
    1484 | 1485 | ## Default parameter 1486 | ```js 1487 | function multiply(a,b=1){ 1488 | //means if no b is passed in if it's undefined. Use this value. 1489 | return a*b; 1490 | } 1491 | multiply(4); // 4 1492 | multiply(4,3); // 12 1493 | ``` 1494 | 1495 | ## Spread 1496 | It does many things. 1497 |
    1498 | Spread syntax allows an iterable such as an array to be expanded in places where zero or more arguments(for function calls) or elements(for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs(for object literals) are expected. 1499 | 1500 | ```js 1501 | function sum(x, y, z) { 1502 | return x + y + z; 1503 | } 1504 | 1505 | const numbers = [1, 2, 3]; 1506 | 1507 | console.log(sum(...numbers)); 1508 | // expected output: 6 1509 | console.log(sum.apply(null, numbers)); 1510 | // expected output: 6 1511 | ``` 1512 | 1513 | ### Spread in array literals 1514 | In array literals - 1515 |
    1516 | Create a new array using an existing array. Spreads the elements from one array into a new array. 1517 | 1518 | ```js 1519 | const n1 = [1,2,3]; 1520 | const n2 = [4,5,6]; 1521 | [...n1,...n2]; 1522 | // [1,2,3,4,5,6] 1523 | 1524 | ['a','b',...n2]; 1525 | // ["a","b",4,5,6] 1526 | 1527 | const a = [1,2,3] 1528 | const b = [23] 1529 | b.push(...a) 1530 | console.log(b) 1531 | // [23, 1, 2, 3] 1532 | ``` 1533 | 1534 | #### In object literals 1535 | copies properties from one object into another object literal. 1536 | 1537 | ```js 1538 | const dog = {name: "Joolie",age:6}; 1539 | const animal = {...dog, isPet: true}; 1540 | // {name: "Joolie",age:6,isPet: true} 1541 | ``` 1542 | 1543 | ## The arguments object 1544 |
  • Available inside every function 1545 |
  • It's like an array-like object 1546 |
    Has a length property 1547 |
    Does not have array methods like push/pop 1548 |
  • Contains all the arguments passed to the function 1549 |
  • Not available inside of arrow functions 1550 | 1551 | ```js 1552 | function sumAll(){ 1553 | let total = 0; 1554 | for(let i=0; i< arguments.length; i++){ 1555 | total += arguments[i]; 1556 | } 1557 | return total; 1558 | } 1559 | sumAll(8,3,4,5); 1560 | ``` 1561 | 1562 | ## Rest (...) Params 1563 | collects all remaining arguments into an actual array. 1564 | 1565 | ```js 1566 | function sum(...numbers){ 1567 | return nums.reduce((t,c)=>{ 1568 | return t+c; 1569 | }) 1570 | } 1571 | // we can use this in arrow function 1572 | const fullName = (firstName, secondName, ...titles)=>{ 1573 | console.log('first',firstName) 1574 | console.log('second',secondName) 1575 | console.log('titles',titles) 1576 | } 1577 | ``` 1578 | 1579 | 1580 | ## Destructuring 1581 | A short, clean syntax to 'unpack': 1582 |
  • values from arrays 1583 |
  • Properties from objects 1584 | Into distinct variables. 1585 | 1586 | ### Destructuring arrays 1587 | ```js 1588 | const arr = [223,535,536]; 1589 | const [one,two,three] = arr; 1590 | one// 223 1591 | two // 535 1592 | three // 536 1593 | 1594 | const [one, ...everyElse] = arr; 1595 | one // 223 1596 | everyElse // [535,536] 1597 | ``` 1598 | 1599 | ### Destructuring objects 1600 | ```js 1601 | const runner = { 1602 | first : "Eliud", 1603 | last: "Kipchoge", 1604 | country: "Kenya", 1605 | title: "Elder of the order of the golden heart of kenya" 1606 | } 1607 | 1608 | const {first, last, country} = runner; 1609 | first // "Eliud" 1610 | last // "Kipchoge" 1611 | country // "Kenya" 1612 | 1613 | const {country: nation} = runner; 1614 | nation // "Kenya" 1615 | ``` 1616 | 1617 | ### Parameters destructuring 1618 | ```js 1619 | const fullName = ({first,last})=>{ 1620 | return `${first} ${last}` 1621 | } 1622 | const runner = { 1623 | first : "Eliud", 1624 | last: "Kipchoge", 1625 | country: "Kenya", 1626 | title: "Elder of the order of the golden heart of kenya" 1627 | } 1628 | fullName(runner); // Eliud Kipchoge 1629 | ``` 1630 | 1631 |

    Object Methods and the "This" Keyword

    1632 | 1633 | ### Short hand properties 1634 | ```js 1635 | const a = 12; 1636 | const t = "Tushar"; 1637 | const n = {a,t}; 1638 | console.log(n) 1639 | // {a: 12, t: "Tushar"} 1640 | ``` 1641 | 1642 | ### Computed Properties 1643 | we can use a variable as a key name in an object literal property. 1644 | ```js 1645 | const role = 'SDE'; 1646 | const person = "Tushar"; 1647 | const role2 = 'Sys Admin'; 1648 | const person2 = 'Navneet'; 1649 | 1650 | const team = {}; 1651 | team[role] = person; 1652 | team[role2] = person2; 1653 | // or 1654 | const team = { 1655 | [role]: person, 1656 | [role2]: person2, 1657 | [23+34]: 'Another' 1658 | } 1659 | 1660 | const addProp = (obj,k,v)=>{ 1661 | return{ 1662 | ...obj, 1663 | [k]:v 1664 | } 1665 | } 1666 | ``` 1667 | 1668 | ## Methods 1669 | We can add functions as properties on objects. 1670 | 1671 | we call them methods. 1672 | 1673 | ```js 1674 | const math ={ 1675 | multiply: function(x,y){ 1676 | return x*y; 1677 | }, 1678 | divide: function(x,y){ 1679 | return x/y; 1680 | } 1681 | } 1682 | ``` 1683 | 1684 | ### Method short hand syntax 1685 | we do this so often that there's a new shorthand way ofadding methods. 1686 | 1687 | ```js 1688 | const math = { 1689 | msg: "Hii this is math", 1690 | add(x,y){ 1691 | return x+y; 1692 | } 1693 | multiply(x,y){ 1694 | return x*y 1695 | } 1696 | } 1697 | 1698 | math.add(40,50) // 90 1699 | ``` 1700 | 1701 | ## This keyword 1702 | The JavaScript this keyword refers to the object it belongs to. It has different values depending on where it is used: ... In a function, this refers to the global object. 1703 | 1704 | 1705 | It has different values depending on where it is used: 1706 |
  • In a method, this refers to the owner object. 1707 |
  • Alone, this refers to the global object. 1708 |
  • In a function, this refers to the global object. 1709 |
  • In a function, in strict mode, this is undefined. 1710 |
  • In an event, this refers to the element that received the event. 1711 |
  • Methods like call(), and apply() can refer this to any object. 1712 | 1713 | >The value of this depends on the invocation context the unction it is used in. 1714 | 1715 | ```js 1716 | const person = { 1717 | first: "Tushar", 1718 | last : "Rajpoot", 1719 | nickName: false, 1720 | fullName(){ 1721 | // console.log(this) 1722 | return `${this.first} ${this.last}` 1723 | }, 1724 | printBio(){ 1725 | const fullName = this.fullName(); 1726 | console.log(`${fullName} is a person`) 1727 | } 1728 | } 1729 | ``` 1730 | > We should not use arrow functions in methods 1731 | 1732 | 1733 |

    Document Object Model

    1734 |
  • The DOM is a JavaScript representation of a webpage. 1735 |
  • It's your JS "window" into the contents of a webpage 1736 |
  • It's just a bunch of objects that you can interact with via JS. 1737 | 1738 | ### The Document Object 1739 | The document object is our entry point into the world of the DOM. It contains representations of all the content on a page, plus tons of useful methods and properties. 1740 | 1741 | ### Selecting 1742 |
  • getElementById 1743 |
  • getElementsByTagName 1744 |
  • getElementsByClassName 1745 | 1746 | #### querySelector 1747 |
  • A newer, all-in-one method to select a single element. 1748 |
  • Pass in a CSS selector 1749 | 1750 | ```js 1751 | const btn = document.querySelector(".red") 1752 | ``` 1753 | 1754 | 1755 | #### querySelectorAll 1756 | Same idea but it selects a collection of elements. 1757 | 1758 | ```js 1759 | const buttons = document.querySelector(".red") 1760 | ``` 1761 | 1762 | ### properties and methods 1763 | 1764 |
  • classList 1765 |
  • getAttribute() 1766 |
  • setAttribute() 1767 |
  • appendChild() 1768 |
  • append() 1769 |
  • prepend() 1770 |
  • removeChild() 1771 |
  • remove() 1772 |
  • createElement 1773 |
  • innerText 1774 |
  • textContent 1775 |
  • innerHTML 1776 |
  • value 1777 |
  • parentElement 1778 |
  • children 1779 |
  • nextSibling 1780 |
  • previousSibling 1781 |
  • style 1782 | 1783 | ### Events in DOM 1784 | Responding to user inputs and actions ! 1785 | 1786 |
  • clicks 1787 |
  • drags 1788 |
  • drops 1789 |
  • hovers 1790 |
  • scrolls 1791 |
  • form submission 1792 |
  • key presses 1793 |
  • focus/blur 1794 |
  • mouse wheel 1795 |
  • double click 1796 |
  • copying 1797 |
  • pasting 1798 |
  • audio start 1799 |
  • screen resize 1800 |
  • printing 1801 | 1802 | 1803 | ### addEventListener 1804 | Specify the event type and a callback to run. 1805 | 1806 | ```js 1807 | const button = document.querySelector("h1"); 1808 | button.addEventListener("click",()=>{ 1809 | alert("You clicked me") 1810 | }) 1811 | ``` 1812 | 1813 | 1814 | ### getAttribute() and setAttribute() 1815 | 1816 | ```js 1817 | const btn = document.querySelector('input[type="submit"]') 1818 | 1819 | btn.getAttribute('type') 1820 | >"submit" 1821 | btn.setAttribute('type','new') 1822 | ``` 1823 | 1824 | ### finding parent/children/sibling 1825 | 1826 | ```js 1827 | element.parentElement 1828 | element.children 1829 | element.nextSibling 1830 | element.previousSibling 1831 | ``` 1832 | 1833 | ### changing multiple elements 1834 | 1835 | ```js 1836 | const buttons = document.querySelectorAll('.btn') 1837 | buttons.forEach((e)=>{ 1838 | e.innerText = 'new Button' 1839 | }) 1840 | ``` 1841 | 1842 | ### Altering styles 1843 | every element has a style property. 1844 | 1845 | we can use the style property to change colors or styles we can change any of those properties and they will be affected on the page but if we're trying to use the style property to read existing properties to read existing styles it won't work unless those styles are defined inline. 1846 | 1847 | #### getComputedStyle 1848 | ```js 1849 | let styles = getComputedStyle(h1) 1850 | ``` 1851 | 1852 | ### Manipulating classes 1853 | 1854 | ```js 1855 | todo.setAttribute("class","done") 1856 | // remove a class 1857 | todo.classList.remove('done') 1858 | // add a class 1859 | todo.classlist.add('done') 1860 | // check element has class or not 1861 | todoAdd.getAttribute('class').includes('done') 1862 | // toggle will remove if class exist and add class if it doesn't' 1863 | todoAdd.classList.toggle('done') 1864 | ``` 1865 | 1866 | 1867 | ### Creating elements 1868 | 1869 | ```js 1870 | let h1 = document.createElement('h1') 1871 | h1.innerText = "This is heading 1" 1872 | // add class to the element 1873 | h1.classList.add('heading') 1874 | // add an id to the element 1875 | h1.setAttribute('id','heading1') 1876 | 1877 | // add an element to the existing element 1878 | const section = document.querySelector('section') 1879 | const newImg = document.createElement('img') 1880 | newImg.setAttribute('src',url) 1881 | section.appendChild(newImg) 1882 | ``` 1883 | 1884 | ### append, prepend and insertBefore 1885 | 1886 | ```js 1887 | const parentUl = document.querySelector('ul') 1888 | const newLi = document.createElement('li') 1889 | newLi.innerText = "Tushar" 1890 | parentUl.appendChild(newLi) 1891 | const firstLi = document.querySelector('li')​ 1892 | parentUl.insertBefore(newLi,firstLi) 1893 | ``` 1894 | 1895 | #### insertAdjacentElement 1896 | 1897 | 1898 | ```js 1899 | element.insertAdjacentHTML(position, text); 1900 | ``` 1901 | 1902 | >'beforebegin': Before the element itself. 1903 | >'afterbegin': Just inside the element, before its first child. 1904 | >'beforeend': Just inside the element, after its last child. 1905 | >'afterend': After the element itself. 1906 | 1907 | ```HTML 1908 | 1909 |

    1910 | 1911 | foo 1912 | 1913 |

    1914 | 1915 | ``` 1916 | ```js 1917 | const le = document.createElement('li') 1918 | h1.insertAdjacentElement('beforebegin',le) 1919 | ``` 1920 | 1921 | #### append() 1922 | ```js 1923 | firstP.append(i,newLi); 1924 | firstP.prepend(i,newLi) 1925 | ``` 1926 | 1927 | #### removeChild() 1928 | ```js 1929 | const ul = document.querySelector('ul')​ 1930 | const removeMe = ul.querySelector('.special')​ 1931 | ul.removeChild(removeMe) 1932 | ``` 1933 | 1934 | #### remove() 1935 | > doesn't need parent element 1936 | 1937 | ```js 1938 | removeMe.remove() 1939 | ``` 1940 | 1941 |

    DOM Events

    1942 | 1943 | #### Responding to user inputs and actions. 1944 | 1945 |
  • clicks 1946 |
  • drags 1947 |
  • drops 1948 |
  • hovers 1949 |
  • scrolls 1950 |
  • form submission 1951 |
  • key presses 1952 |
  • focus/blur 1953 |
  • mouse wheel 1954 |
  • double click 1955 |
  • copying 1956 |
  • pasting 1957 |
  • audio start 1958 |
  • screen resize 1959 |
  • printing 1960 | 1961 | ## Using Events 1962 | ### using on 1963 | ```HTML 1964 | 1965 | ``` 1966 | >More content will be added soon for events 1967 |
    1968 | 1969 | 1970 | 1971 |

    Asynchronous JavaScript, Callbacks and Promises

    1972 | 1973 | ## Call Stack 1974 | The mechanism the JS interpreter uses to keep track of its place in a script that calls multiple functions. 1975 | 1976 | How JS "knows" what function is currently being run and what functions are called from within that function etc. 1977 | 1978 | ### How it works 1979 | 1980 |
  • When a script calls a function, the interpreter adds it to the call stack and then starts carrying out the function. 1981 | 1982 |
  • Any functions that are called by that function are added the call stack further up, and run where their callls are reached 1983 | 1984 |
  • When the current function is finished, the interpreter takes it off the stack and resumes execution where it left off the last code listing. 1985 | 1986 | >Stack is a linear data structure which follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). There are many real-life examples of a stack 1987 | 1988 | ```js 1989 | const multiply = (x,y) => x*y; 1990 | const square = (x) => multiply(x,x); 1991 | 1992 | const isRightTriangle = (a,b,c)=>{ 1993 | return square(a) + square(b)=== square(c); 1994 | } 1995 | 1996 | isRightTriangle(3,4,5); 1997 | // square(3) + square(4)===square(4) 1998 | 1999 | ``` 2000 | 2001 | ## JavaScript is a single threaded language 2002 | At any given point in time, that single JS thread is running at most one line of JS code. 2003 | 2004 | 2005 | ## How asynchronous callbacks actually work? 2006 | 2007 |
  • Browsers come with web APIs that are able to handle certain tasks in the background (like making requests or setTimeout) 2008 |
  • The JS call stack regocnizes these web API functions and passes them off to the browser to take care of 2009 |
  • Once the browser finishes those tasks, they return and are pushed onto the stack as a callback. 2010 | 2011 | try your code here :- click here 2012 | 2013 | 2014 | ## Callback Hell 2015 | 2016 | ### What is Synchronous Javascript? 2017 | In Synchronous Javascript, when we run the code, the result is returned as soon as the browser can do. Only one operation can happen at a time because it is single-threaded. So, all other processes are put on hold while an operation is executing. 2018 | 2019 | ### What is Asynchronous Javascript? 2020 | 2021 |
  • Some functions in Javascript requires AJAX because the response from some functions are not immediate. It takes some time and the next operation cannot start immediately. It has to wait for the function to finish in the background. In such cases, the callbacks need to be asynchronous. 2022 |
  • There are some external Javascript Web APIs that allows AJAX – Asynchronous Javascript and XML. 2023 | In AJAX, many operations can be performed simultaneously. 2024 | 2025 | ### What is a callback? 2026 | 2027 |
  • Callbacks are nothing but functions that take some time to produce a result. 2028 |
  • Usually these async callbacks (async short for asynchronous) are used for accessing values from databases, downloading images, reading files etc. 2029 |
  • As these take time to finish, we can neither proceed to next line because it might throw an error saying unavailable nor we can pause our program. 2030 |
  • So we need to store the result and call back when it is complete. 2031 | 2032 | ### What is callback hell? 2033 | This is a big issue caused by coding with complex nested callbacks. Here, each and every callback takes an argument that is a result of the previous callbacks. In this manner, The code structure looks like a pyramid, making it difficult to read and maintain. Also, if there is an error in one function, then all other functions get affected. 2034 | 2035 | # Promises 2036 | A promise is an object representing the eventual completion or failure of an asynchronous operation. 2037 | 2038 | > A Pattren for writing async code. 2039 | 2040 | A promise is a returned object to which we can attach callbacks, instead of passing callbacks into a function. 2041 | 2042 | when we create a promise, we pass in a function. And this function has two parameters. Always these two parameters we usually call resolve and reject. And these are actually functions. 2043 | 2044 | Inside of inside promise function if we call resolve, the promise will be resolved. If we call reject, the promise will be rejected. 2045 | 2046 |
  • If we don't resolve or reject it, it's status will be pending. 2047 |
  • If we reject it, our promise status will be rejected. 2048 |
  • If we resolve it, promise status will be resolved. 2049 | 2050 | 2051 | 2052 | ```js 2053 | // create a promise which resolved using a random number 2054 | const getMePhone = new Promise((resolve,reject) => { 2055 | let rand = Math.random() 2056 | if(rand<0.5){ 2057 | resolve() 2058 | } 2059 | else{ 2060 | reject() 2061 | } 2062 | 2063 | }) 2064 | ``` 2065 | 2066 | #### How do I run code if this promise was rejected versus run code, if this promise was resolved? 2067 | .then: every promise has a then method. this then method will run if our promise is resolved. 2068 | 2069 | .catch Every promise has a catch method also. We can chain it with .then or we can write along with promise. 2070 | 2071 | ```js 2072 | getMePhone.then(()=>{ 2073 | console.log("Yeah I got a Phone") 2074 | }).catch(()=>{ 2075 | console.log("No Phone") 2076 | }) 2077 | ``` 2078 | 2079 | 2080 | 2081 | ## Returning promises from Functions 2082 | 2083 | ```js 2084 | // returning a promise from a function 2085 | const makeDogPromise = () => { 2086 | return new Promise((resolve, reject) => { 2087 | setTimeout(() => { 2088 | const rand = Math.random(); 2089 | if (rand < 0.5) { 2090 | resolve() 2091 | } 2092 | else 2093 | reject() 2094 | }, 5000) 2095 | }) 2096 | } 2097 | makeDogPromise().then(()=>{ 2098 | console.log("hello") 2099 | }) 2100 | ``` 2101 | 2102 | ## Resolving/rejecting promises with values 2103 | we can pass information in to the resolve or reject calls. 2104 | ```js 2105 | const fakeRequest = (url)=>{ 2106 | return new Promise((resolve,reject)=>{ 2107 | setTimeout(()=>{ 2108 | const pages = { 2109 | '/users' : "Users pages", 2110 | '/about' : "About page" 2111 | } 2112 | const data = pages[url] 2113 | if(data){ 2114 | 2115 | resolve(pages[url]) 2116 | } 2117 | else{ 2118 | reject({status:400}) 2119 | } 2120 | },2000) 2121 | }) 2122 | } 2123 | 2124 | fakeRequest('/users').then((data)=>{ 2125 | console.log(data) 2126 | }).catch((res)=>{console.log(res.status)}) 2127 | ``` 2128 | 2129 | ## Promise Chaining 2130 | ```js 2131 | const fakeRequest = (url) => { 2132 | return new Promise((resolve, reject) => { 2133 | setTimeout(() => { 2134 | const pages = { 2135 | '/users': [ 2136 | { id: 1, username: 'Tushar' }, 2137 | { id: 5, username: 'Rahul' } 2138 | ], 2139 | '/users/1': { 2140 | id: 1, 2141 | username: 'Tushar', 2142 | country: 'India', 2143 | work: 'Noida', 2144 | role: 'Software Engineer', 2145 | postid: 54 2146 | }, 2147 | '/users/5': { 2148 | id: 5, 2149 | username: 'Rahul', 2150 | country: 'India', 2151 | work: 'Noida', 2152 | role: 'DevOps Engineer' 2153 | }, 2154 | '/posts/54': { 2155 | id: 54, 2156 | title: 'My new Post', 2157 | 2158 | }, 2159 | '/about': "About page" 2160 | } 2161 | 2162 | const data = pages[url] 2163 | if (data) { 2164 | resolve(pages[url]) 2165 | } 2166 | else { 2167 | reject({ status: 400 }) 2168 | } 2169 | }, 2000) 2170 | }) 2171 | } 2172 | 2173 | fakeRequest('/users').then((data) => { 2174 | let id = data[0].id; 2175 | return fakeRequest(`/users/${id}`) 2176 | }) 2177 | .then((data) => { 2178 | // console.log(data) 2179 | let postid = data.postid; 2180 | return fakeRequest(`/posts/${postid}`) 2181 | }) 2182 | .then((data) => { 2183 | console.log(data) 2184 | }) 2185 | .catch((err) => { console.log(err) }) 2186 | ``` 2187 | 2188 |
    2189 | 2190 |

    Making http requests

    2191 | 2192 |
  • XMLHTTP (old standard method) 2193 |
  • Fetch (a better way) 2194 |
  • Axios (a third party library) 2195 | 2196 | ## What is AJAX? 2197 | Asynchronous Javascript and XML.
    2198 | AJAX is a technique for accessing web servers from a web page. 2199 |
  • Read data from a web server - after a web page has loaded 2200 |
  • Update a web page without reloading the page 2201 |
  • Send data to a web server - in the background 2202 | 2203 | ### AJAX just uses a combination of:
    2204 | A browser built-in XMLHttpRequest object (to request data from a web server) 2205 | JavaScript and HTML DOM (to display or use the data) 2206 | 2207 | 2208 | AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. 2209 | 2210 | 2211 | 2212 | 1. An event occurs in a web page (the page is loaded, a button is clicked) 2213 | 2. An XMLHttpRequest object is created by JavaScript 2214 | 3. The XMLHttpRequest object sends a request to a web server 2215 | 4. The server processes the request 2216 | 5. The server sends a response back to the web page 2217 | 6. The response is read by JavaScript 2218 | 7. Proper action (like page update) is performed by JavaScript 2219 | 2220 | ## XML and JSON 2221 | AJAJ- Asyncrhonous Javascript and JSON . 2222 | 2223 | XML and JSON are two ways of basically formatting data so that you can send it from a server to another server or a server to a browser. 2224 | 2225 | ### XML Format 2226 | 2227 | ```XML 2228 | 2229 | Tove 2230 | Jani 2231 | Reminder 2232 | Don't forget me this weekend! 2233 | 2234 | ``` 2235 | 2236 | ### JSON Format 2237 | (JavaScript Object Notation) 2238 | 2239 | ```JSON 2240 | { 2241 | "employee": { 2242 | "name": "sonoo", 2243 | "salary": 56000, 2244 | "married": true 2245 | } 2246 | } 2247 | ``` 2248 | 2249 |
  • JSON is not JS object 2250 |
  • Every key in JSON must be a string 2251 |
  • We can also use arrays in JSON 2252 |
  • We can easily translate between JSON to JavaScript 2253 | 2254 | ## XMLHttpRequest 2255 |
  • The "original" way of sending requests via JS. 2256 |
  • Does not support promises, so... lots of callbacks 2257 |
  • WTF is going on with the weird capitalization 2258 |
  • Clunky syntax that I find difficult to remember. 2259 | 2260 | ```js 2261 | const myReq = new XMLHttpRequest(); 2262 | myReq.onload = function(){ 2263 | const data = JSON.parse(this.responceText) 2264 | console.log(data); 2265 | } 2266 | myReq.onerror = (err)=>{ 2267 | console.log("Error",err) 2268 | } 2269 | myReq.open('get','sample.com',true); 2270 | myReq.setRequestHeader('Accept','application/json'); 2271 | myReq.send(); 2272 | console.log(myReq.response) 2273 | ``` 2274 | 2275 | ## Making requests using fetch 2276 |
  • The newer way of making requests via JS. 2277 |
  • Supports promises. 2278 |
  • Not supported in Internet Explorer. 2279 | 2280 | ```js 2281 | fetch('url',{header: { Accept: 'application/json'}}) 2282 | .then((res)=> { 2283 | if(res.status!=200){ 2284 | console.log("Problem",res.status) 2285 | return; 2286 | } 2287 | res.json().then((data)=> { 2288 | console.log(data) 2289 | }) 2290 | 2291 | }) 2292 | .catch((err)=> {console.log(err)}) 2293 | ``` 2294 | ### Chaining fetch requests 2295 | 2296 | ```js 2297 | const url = "https://swapi.dev/api/planets"; 2298 | fetch(url).then((res)=>{ 2299 | return res.json() 2300 | 2301 | }) 2302 | .then((data)=>{ 2303 | return data.results 2304 | }) 2305 | .then((results)=>{ 2306 | const filmUrl = results[0].films[0]; 2307 | return fetch(filmUrl) 2308 | }) 2309 | .then((results)=>{ 2310 | return results.json() 2311 | }).then((data)=>{ 2312 | console.log(data) 2313 | }) 2314 | .catch((err)=>{console.log(err)}) 2315 | ``` 2316 | 2317 | ### Refactoring fetch requests 2318 | ```js 2319 | const checkStatusAndParse = (response)=>{ 2320 | if(!response.ok) throw new Error('Status code error') 2321 | return response.json(); 2322 | } 2323 | const printPlanets = (data)=>{ 2324 | console.log("FETCHED ALL PLANETS") 2325 | data.results.forEach((planet)=>{ 2326 | console.log(planet.name) 2327 | }) 2328 | return Promise.resolve(data.next) 2329 | } 2330 | 2331 | const fetchMorePlanets = (url)=>{ 2332 | return fetch(url); 2333 | } 2334 | 2335 | fetch(url) 2336 | .then(checkStatusAndParse) 2337 | .then(printPlanets) 2338 | .then(fetchMorePlanets) 2339 | .then(checkStatusAndParse) 2340 | .then(printPlanets) 2341 | .catch((err)=>{console.log(err)}) 2342 | ``` 2343 | 2344 | ## Axios 2345 |
  • A library for making http requests. 2346 | 2347 | ```js 2348 | axios.get(url).then((res)=>{ 2349 | console.log(res.data) 2350 | }) 2351 | .catch((err)=>{ 2352 | console.log(err) 2353 | }) 2354 | ``` 2355 | 2356 | ## Sequential requests using axios 2357 | ```js 2358 | const showData = ({data})=>{ 2359 | data.results.forEach((planet) => { 2360 | console.log(planet.name) 2361 | }) 2362 | return axios.get(data.next) 2363 | } 2364 | 2365 | axios.get(url) 2366 | .then(showData) 2367 | .then(showData) 2368 | ``` 2369 | 2370 |
    2371 | 2372 | 2373 |

    Async and Await

    2374 | 2375 | ## The async keyword 2376 |
  • Async functions always return a promise. 2377 |
  • If the function returns a value, the promise will be resolved with that value. 2378 |
  • If the function throws an exception, the promise will be rejected. 2379 | 2380 | ```JS 2381 | async function hello(){ 2382 | return "Hey Guys" 2383 | } 2384 | hello(); 2385 | // Promise(: "Hey Guys") 2386 | async function huh(){ 2387 | throw new Error("Oh no") 2388 | } 2389 | huh(); 2390 | // Promise(: Error: oh no) 2391 | const add = async (a,b) => { 2392 | return a+b; 2393 | } 2394 | 2395 | add(24,35).then((value) => {console.log(value)}) 2396 | ``` 2397 | 2398 | ## The Await keyword 2399 |
  • We can only use the await keyword inside of function declared with async. 2400 |
  • Await will pause the execution of the function, waiting for a promise to be resolved. 2401 | 2402 | ```JS 2403 | async function getData(){ 2404 | const res = await axios.get('https://swapi.dev/api/planets') 2405 | console.log(res.data) 2406 | } 2407 | ``` 2408 | 2409 | ## Error handling in async Functions 2410 |
  • We can use catch while calling the async function as we know async functions always return promise. 2411 | 2412 | ```JS 2413 | getData().catch((err) => {console.log(err)}) 2414 | ``` 2415 | 2416 |
  • We can add a try and catch block 2417 | 2418 | ```JS 2419 | async function getData(){ 2420 | try{ 2421 | const res = await axios.get('https://swapi.dev/api/planets') 2422 | console.log(res.data) 2423 | } 2424 | catch(err){ 2425 | console.log(err) 2426 | } 2427 | } 2428 | ``` 2429 | 2430 | ## Multiple Awaits 2431 | 2432 | ```JS 2433 | async function animateRight(el, amt) { 2434 | await moveX(el, amt, 1000); 2435 | await moveX(el, amt, 1000); 2436 | await moveX(el, amt, 1000); 2437 | await moveX(el, amt, 1000); 2438 | await moveX(el, amt, 1000); 2439 | await moveX(el, amt, 1000); 2440 | await moveX(el, amt, 1000); 2441 | await moveX(el, amt, 1000); 2442 | await moveX(el, amt, 1000); 2443 | await moveX(el, amt, 1000); 2444 | } 2445 | ``` 2446 | 2447 | ## Parallel vs Sequential requests 2448 | 2449 | ```JS 2450 | // SEQUENTIAL REQUEST 2451 | async function getData(){ 2452 | // if I want to request 3 urls 2453 | const res = await axios.get("https://pokeapi.co/api/v2/pokemon/1") 2454 | const res2 = await axios.get("https://pokeapi.co/api/v2/pokemon/2") 2455 | const res3 = await axios.get("https://pokeapi.co/api/v2/pokemon/3") 2456 | console.log(res.data) 2457 | } 2458 | ``` 2459 | 2460 | These requests are happening in sequence, like second request will happen when first done. 2461 | 2462 | 2463 | #### Awaiting in parallel 2464 | 2465 | ```JS 2466 | async function getData(){ 2467 | // if I want to request 3 urls 2468 | const res = axios.get("https://pokeapi.co/api/v2/pokemon/1") 2469 | const res2 = axios.get("https://pokeapi.co/api/v2/pokemon/2") 2470 | const res3 = axios.get("https://pokeapi.co/api/v2/pokemon/3") 2471 | const poke1 = await res 2472 | const poke2 = await res2 2473 | const poke3 = await res3 2474 | // now res, res2, res3 are promises not data 2475 | console.log(poke1.data) 2476 | } 2477 | ``` 2478 | 2479 | ## Refactoring with Promise.all 2480 | 2481 | Promise.all accepts an array of promises. 2482 | 2483 | ```JS 2484 | async function getData(){ 2485 | const res = axios.get("https://pokeapi.co/api/v2/pokemon/1") 2486 | const res2 = axios.get("https://pokeapi.co/api/v2/pokemon/2") 2487 | const res3 = axios.get("https://pokeapi.co/api/v2/pokemon/3") 2488 | const results = await Promise.all([res,res2,res3]) 2489 | console.log(results) 2490 | } 2491 | ``` 2492 | 2493 | 2494 |

    Prototypes, Classes, & the new operator

    2495 | 2496 | ## What are protoypes? 2497 | Prototypes are the mechanism by which JavaScript objects inherit features from one another. 2498 | 2499 | ### A prototype-based language? 2500 | JavaScript is often described as a prototype-based language — to provide inheritance, objects can have a prototype object, which acts as a template object that it inherits methods and properties from. 2501 | 2502 | An object's prototype object may also have a prototype object, which it inherits methods and properties from, and so on. This is often referred to as a prototype chain, and explains why different objects have properties and methods defined on other objects available to them. 2503 | 2504 | We can define prototypes of string like 2505 | 2506 | ```JS 2507 | String.prototype.getup = function(){ 2508 | return this.toUpperCase() 2509 | } 2510 | ``` 2511 | 2512 | We can change already defined protoypes as well. For example 2513 | 2514 | ```JS 2515 | Array.prototype.pop = function(){ 2516 | return "Sorry" 2517 | } 2518 | ``` 2519 | 2520 | ## Object Oriented Programming in JavaScript 2521 | 2522 | There are certain features or mechanisms which makes a Language Object-Oriented like: 2523 | 2524 |
  • Object 2525 |
  • Classes 2526 |
  • Encapsulation 2527 |
  • Inheritance 2528 | 2529 | ###
  • Object 2530 | An Object is an instance of a class. Objects are everywhere in JavaScript almost every element is an Object whether it is a function, array, and string. 2531 | 2532 | >A Method in javascript is a property of an object whose value is a function. 2533 | 2534 | Object can be created in two ways in JavaScript: 2535 |
      2536 |
    1. Using an Object Literal 2537 | 2538 | ```JS 2539 | //Defining object 2540 | let person = { 2541 | first_name:'Mukul', 2542 | last_name: 'Latiyan', 2543 | 2544 | //method 2545 | getFunction : function(){ 2546 | return (`The name of the person is 2547 | ${person.first_name} ${person.last_name}`) 2548 | }, 2549 | //object within object 2550 | phone_number : { 2551 | mobile:'12345', 2552 | landline:'6789' 2553 | } 2554 | } 2555 | console.log(person.getFunction()); 2556 | console.log(person.phone_number.landline); 2557 | ``` 2558 | 2559 |
    2. Using an Object Constructor 2560 | 2561 | ```JS 2562 | //using a constructor 2563 | function person(first_name,last_name){ 2564 | this.first_name = first_name; 2565 | this.last_name = last_name; 2566 | } 2567 | //creating new instances of person object 2568 | let person1 = new person('Mukul','Latiyan'); 2569 | let person2 = new person('Rahul','Avasthi'); 2570 | 2571 | console.log(person1.first_name); 2572 | console.log(`${person2.first_name} ${person2.last_name}`); 2573 | ``` 2574 |
    2575 |
  • Using Object.create() method:
    The Object.create() method creates a new object, using an existing object as the prototype of the newly created object. 2576 | 2577 | ```JS 2578 | // Object.create() example a 2579 | // simple object with some properties 2580 | const coder = { 2581 | isStudying : false, 2582 | printIntroduction : function(){ 2583 | console.log(`My name is ${this.name}. Am I 2584 | studying?: ${this.isStudying}.`) 2585 | } 2586 | } 2587 | // Object.create() method 2588 | const me = Object.create(coder); 2589 | 2590 | // "name" is a property set on "me", but not on "coder" 2591 | me.name = 'Mukul'; 2592 | 2593 | // Inherited properties can be overwritten 2594 | me.isStudying = true; 2595 | 2596 | me.printIntroduction(); 2597 | ``` 2598 | 2599 | ###
  • Classes 2600 | Classes are blueprint of an Object. A class can have many Object, because class is a template while Object are instances of the class or the concrete implementation. 2601 | 2602 | ```JS 2603 | // Defining class using es6 2604 | class Vehicle { 2605 | constructor(name, maker, engine) { 2606 | this.name = name; 2607 | this.maker = maker; 2608 | this.engine = engine; 2609 | } 2610 | getDetails(){ 2611 | return (`The name of the bike is ${this.name}.`) 2612 | } 2613 | } 2614 | // Making object with the help of the constructor 2615 | let bike1 = new Vehicle('Hayabusa', 'Suzuki', '1340cc'); 2616 | let bike2 = new Vehicle('Ninja', 'Kawasaki', '998cc'); 2617 | 2618 | console.log(bike1.name); // Hayabusa 2619 | console.log(bike2.maker); // Kawasaki 2620 | console.log(bike1.getDetails()); 2621 | ``` 2622 | 2623 | >unlike other Object Oriented Language there is no classes in JavaScript we have only Object. To be more precise, JavaScript is a prototype based object oriented language, which means it doesn’t have classes rather it define behaviors using constructor function and then reuse it using the prototype. 2624 | 2625 | >JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript’s existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance. 2626 | 2627 | ###
  • Encapsulation 2628 | The process of wrapping property and function within a single unit is known as encapsulation. 2629 | 2630 | ```JS 2631 | //encapsulation example 2632 | class person{ 2633 | constructor(name,id){ 2634 | this.name = name; 2635 | this.id = id; 2636 | } 2637 | add_Address(add){ 2638 | this.add = add; 2639 | } 2640 | getDetails(){ 2641 | console.log(`Name is ${this.name},Address is: ${this.add}`); 2642 | } 2643 | } 2644 | 2645 | let person1 = new person('Mukul',21); 2646 | person1.add_Address('Delhi'); 2647 | person1.getDetails(); 2648 | ``` 2649 | Sometimes encapsulation refers to hiding of data or data Abstraction which means representing essential features hiding the background detail. 2650 | 2651 | ###
  • Inheritance 2652 | It is a concept in which some property and methods of an Object is being used by another Object. Unlike most of the OOP languages where classes inherit classes, JavaScript Object inherits Object i.e. certain features (property and methods)of one object can be reused by other Objects. 2653 | 2654 | ```JS 2655 | //Inheritance example 2656 | class person{ 2657 | constructor(name){ 2658 | this.name = name; 2659 | } 2660 | //method to return the string 2661 | toString(){ 2662 | return (`Name of person: ${this.name}`); 2663 | } 2664 | } 2665 | class student extends person{ 2666 | constructor(name,id){ 2667 | //super keyword to for calling above class constructor 2668 | super(name); 2669 | this.id = id; 2670 | } 2671 | toString(){ 2672 | return (`${super.toString()},Student ID: ${this.id}`); 2673 | } 2674 | } 2675 | let student1 = new student('Mukul',22); 2676 | console.log(student1.toString()); 2677 | ``` 2678 | 2679 | ## Factory Functions 2680 | ```JS 2681 | function makeColor(r, g, b) { 2682 | const color = {} 2683 | color.r = r; 2684 | color.g = g; 2685 | color.b = b; 2686 | color.rgb = function () { 2687 | const { r, g, b } = this; 2688 | return `rgb(${r}, ${b}, ${g})` 2689 | } 2690 | color.hex = function () { 2691 | const { r, g, b } = this; 2692 | return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1) 2693 | 2694 | } 2695 | return color; 2696 | } 2697 | ``` 2698 | 2699 | This above function makes us an object. This is called factory function. 2700 | 2701 | ## Constructor funcion 2702 | Factory function pattern is not commonly used. 2703 | Instead of this we use constructor pattern or constructor function. 2704 | 2705 | ### The new operator 2706 | The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function. 2707 | 2708 |
    2709 | new constructor[([arguments])]
    2710 | 
    2711 | 2712 | ```JS 2713 | function Car(make,model,year){ 2714 | this.make = make 2715 | this.model = model 2716 | this.year = year 2717 | } 2718 | 2719 | let car1 = new Car("Audi", "Q7", "2022") 2720 | ``` 2721 | 2722 |
  • constructor
    2723 | A class or function that specifies the type of the object instance. 2724 | 2725 |
  • arguments
    2726 | A list of values that the constructor will be called with. 2727 |
      2728 |
    1. Creates a blank, plain JavaScript object. 2729 |
    2. Adds a property to the new object (__proto__) that links to the constructor function's prototype object 2730 |
    3. Binds the newly created object instance as the this context (i.e. all references to this in the constructor function now refer to the object created in the first step). 2731 |
    4. Returns this if the function doesn't return an object.
    2732 | 2733 | 2734 | ## Classes in JavaScript 2735 | Whenever we define a class, we define a constructor() inside of it. Constructor is a function which will run immediately when a object is created using this class. 2736 | 2737 | ```JS 2738 | class Color{ 2739 | constructor(r,g,b){ 2740 | console.log("INSIDE CONSTRUCTOR") 2741 | console.log(r,g,b) 2742 | 2743 | } 2744 | } 2745 | 2746 | const c1 = new Color(333,43,34) 2747 | ``` 2748 | 2749 | We can define object methods in class 2750 | 2751 | ```JS 2752 | class Color{ 2753 | constructor(r,g,b){ 2754 | this.r = r 2755 | this.g = g 2756 | this.b = b 2757 | } 2758 | greet(){ 2759 | const {r,g,b} = this 2760 | return `rgb(${r}, ${g}, ${b})` 2761 | } 2762 | } 2763 | 2764 | const c1 = new Color(333,43,34) 2765 | ``` 2766 | 2767 | ## Extends, Super and Subclasses 2768 | We can inherit a class to another class using extends keyword 2769 | 2770 | ```JS 2771 | class Pet { 2772 | constructor(name,age){ 2773 | this.name = name 2774 | this.age = age 2775 | } 2776 | eat(){ 2777 | return `${this.name} is eating` 2778 | } 2779 | } 2780 | 2781 | class Cat extends Pet{ 2782 | meow(){ 2783 | return "MEOWWW" 2784 | } 2785 | } 2786 | 2787 | class Dog extends Pet{ 2788 | bark(){ 2789 | return "BARKWW" 2790 | } 2791 | } 2792 | 2793 | const cat1 = new Cat("Losi",5) 2794 | const dog1 = new Dog("Rockie",7) 2795 | ``` 2796 | 2797 |
  • The super keyword is used to access and call functions on an object's parent. 2798 | 2799 | ```JS 2800 | class Rectangle { 2801 | constructor(height, width) { 2802 | this.name = 'Rectangle'; 2803 | this.height = height; 2804 | this.width = width; 2805 | } 2806 | sayName() { 2807 | console.log('Hi, I am a ', this.name + '.'); 2808 | } 2809 | get area() { 2810 | return this.height * this.width; 2811 | } 2812 | set area(value) { 2813 | this._area = value; 2814 | } 2815 | } 2816 | 2817 | class Square extends Rectangle { 2818 | constructor(length) { 2819 | this.height; // ReferenceError, super needs to be called first! 2820 | 2821 | // Here, it calls the parent class's constructor with lengths 2822 | // provided for the Rectangle's width and height 2823 | super(length, length); 2824 | 2825 | // Note: In derived classes, super() must be called before you 2826 | // can use 'this'. Leaving this out will cause a reference error. 2827 | this.name = 'Square'; 2828 | } 2829 | } 2830 | ``` 2831 | 2832 |
    2833 | 2834 | 2835 |

    JavaScript with Node.js

    2836 | 2837 | 2838 | 2839 | 2840 | 2841 | 2842 | 2843 | 2844 | 2845 | 2846 | 2847 | 2848 | 2849 | 2850 | 2851 | 2852 | 2853 | 2854 | 2855 | 2856 | 2857 | 2858 |
    JS in BrowserJS with Node
    Executed by adding script tags to an HTML documentExecuted by running the NODE CLI from your terminal
    We get access to the DOM and related objects(window)NO DOM exists
    Code can references variables in other files freelyEach file is its own seperte world
    Include libraries by adding script tags(more complicated solutions exist)Include libraries by using NPM(Node Package Manager)
    2859 | 2860 | 2861 | ## Running JS code with Node 2862 | 2863 | ```Bash 2864 | $ node index.js # executes a file in te same directory caled index.js 2865 | 2866 | $ node # enters the NODE REPS 2867 | ``` 2868 | 2869 | ## Working with Modules in Node.js 2870 | If we want to share stuff between different node js files. We can make use of modules 2871 | 2872 | ```JS 2873 | // index.js 2874 | const message = require('./myscript.js') 2875 | console.log(message) 2876 | ``` 2877 | 2878 | ```JS 2879 | // myscript.js 2880 | module.exports = 'Hi' 2881 | ``` 2882 | 2883 | ```Bash 2884 | $ node index.js 2885 | ``` 2886 | 2887 | ## Invisible functions 2888 | If we are running index.js file, node will find index.js file and then it's going to wrap it inside a function like this 2889 | 2890 | ```JS 2891 | function (exports, require, module,__filename, __dirname){ 2892 | const message = require('./myscript.js') 2893 | console.log(message) 2894 | } 2895 | ``` 2896 | 2897 | This is a simple function that has some number of arguments. This function is going to be automatically invoked by node. Here are 5 arguments that are automatically provided. 2898 | 2899 | 2900 | 2901 | 2902 | 2903 | 2904 | 2905 | 2906 | 2907 | 2908 | 2909 | 2910 | 2911 | 2912 | 2913 | 2914 | 2915 | 2916 | 2917 | 2918 | 2919 | 2920 |
    exportsEquivalent to module.exports . We can technically export code using this, but it is easier to use 'module.exports' because of a little corner
    requireFunction to get access to the exports from another file
    moduleObject that defines some properties + informtion about the current file
    __filenameFull path + file name of this file
    __dirnameFull path of this file
    2921 | 2922 | We can check these arguments by running - 2923 | 2924 | ```JS 2925 | console.log(arguments) 2926 | ``` 2927 | 2928 | ## The require cache 2929 | Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file. 2930 | 2931 | > Moules get only required once. 2932 | 2933 | ## Debugging Node js 2934 | 2935 | 2936 | 2937 | 2938 | 2939 | 2940 | 2941 | 2942 | 2943 | 2944 | 2945 | 2946 | 2947 |
    node inspect index.jsStart up a debugger CLI and pause execution whenever a debugger statement is hit
    node --inspect index.jsstart up a debugger instance and pause execution whenever a debugger statement is hit. Access the debugger at 'chrome://inspect'
    node --inspect-brk index.jsStart up a debugger instance and wait to execute until a debugger is connected. Access the debugger at 'chrome://inspect'
    2948 | 2949 | ### CLI Debugger commands 2950 | 2951 | 2952 | 2953 | 2954 | 2955 | 2956 | 2957 | 2958 | 2959 | 2960 | 2961 | 2962 | 2963 | 2964 | 2965 | 2966 | 2967 | 2968 |
    CContinue execution until program ends or next debugger statement
    nRun the next line of code
    sstep in to a function
    oStep out of current function
    2969 | 2970 | #### Accessing Node js standard library modules 2971 | We can access node js provided inbuilt standard library modules using require function. 2972 | 2973 | If we want to use file system we can require fs just like this 2974 | 2975 | ```JS 2976 | const fs = require('fs'); 2977 | ``` 2978 | 2979 | ## callback pattern in Node js 2980 | let's use fs.readdir function which accepts callbacks. 2981 | 2982 | If we want to use current directory, first argument we need to pass '.' in the function. The second argument is callback. 2983 | 2984 | ```JS 2985 | const fs = require('fs'); 2986 | fs.readdir('.',(err,files)=>{ 2987 | if(err){ 2988 | console.log(err) 2989 | } 2990 | console.log(files) 2991 | }) 2992 | ``` 2993 | 2994 | ## Process.cwd function 2995 | cwd means current working directory. 2996 | 2997 | ```JS 2998 | const fs = require('fs'); 2999 | fs.readdir(process.cwd(),(err,files)=>{ 3000 | if(err){ 3001 | console.log(err) 3002 | } 3003 | console.log(files) 3004 | }) 3005 | ``` 3006 | 3007 | ## Running a Node program as an Executable 3008 | 3009 | ```bash 3010 | $ npm init -y 3011 | ``` 3012 | This command will generate a file for us, package.json 3013 | 3014 | ```JSON 3015 | { 3016 | "name": "project-1", 3017 | "version": "1.0.0", 3018 | "description": "", 3019 | "main": "index.js", 3020 | "scripts": { 3021 | "test": "echo \"Error: no test specified\" && exit 1" 3022 | }, 3023 | "keywords": [], 3024 | "author": "", 3025 | "license": "ISC" 3026 | } 3027 | ``` 3028 | 3029 | Here we can see a key "scripts" so these are tiny script that do some automated tasks for us. 3030 | 3031 | We can add another script that try to build our project 3032 | 3033 | ```JSON 3034 | "scripts": { 3035 | "test": "echo \"Error: no test specified\" && exit 1", 3036 | "build": "npm run build" 3037 | }, 3038 | ``` 3039 | 3040 | We can add bin key in this file so that when we run this nls command in our terminal our index.js file will be executed. 3041 | 3042 | ```JSON 3043 | "bin":{ 3044 | "nls": "index.js" 3045 | } 3046 | ``` 3047 | 3048 |
  • Create package.json file with bin section 3049 |
  • Change index.js file permissions 3050 | 3051 | ```bash 3052 | $ chmod +x index.js 3053 | ``` 3054 | 3055 |
  • Add comment to index.js file to allow it to be treated like an executable 3056 | 3057 | ```JS 3058 | #!/usr/bin/env node 3059 | ``` 3060 | 3061 |
  • Link our project 3062 | 3063 | ```bash 3064 | $ npm link 3065 | ``` 3066 | 3067 | Now our project(index.js) file is executable. We can execute it from anywhere in our system just by command nls. 3068 | 3069 | > It's very useful for creating command line tools using node js. 3070 | 3071 | 3072 | ## Options to get to know which file is dir or file 3073 |
  • Maintain an array of results from each lstat. As each callback is invoked, add the stats object to this array. When array is full, log everything in it. 3074 |
  • Wrap the lstat call with a promise, use async/await syntax to process lstat call one at a time 3075 |
  • Wrap the lstat call with a promise, use async/await + the Promise.all helper method to process lstat calls all at once. 3076 | 3077 | let's implement most optimized solution(promise.all based) 3078 | 3079 | ```JS 3080 | #!/usr/bin/env node 3081 | const fs = require('fs'); 3082 | const chalk = require('chalk') 3083 | const {lstat} = fs.promises; 3084 | 3085 | fs.readdir(process.cwd(),async (err,files)=>{ 3086 | if(err){ 3087 | console.log(err) 3088 | } 3089 | const fileAr = files.map((file)=>{return lstat(file)}) 3090 | const stats = await Promise.all(fileAr) 3091 | 3092 | stats.forEach((stat,index)=>{ 3093 | if(stat.isFile()){ 3094 | console.log(chalk.blue(files[index])) 3095 | } 3096 | else{ 3097 | console.log(chalk.green(files[index])) 3098 | } 3099 | }) 3100 | }) 3101 | ``` 3102 | 3103 | ## Taking inputs from commandline 3104 | 3105 | If we console.log process.argv this will return an array and whatever we pass with our executable command that will be pushed into this array. 3106 | 3107 | ```JS 3108 | console.log(process.argv) 3109 | ``` 3110 | 3111 |
    3112 | 3113 | ### Thanks for reading this.. 3114 | 3115 |
    3116 | 3117 | ## Author: Tushar Rajpoot 3118 | ## Publication: Kubekode 3119 | 3120 |

    3121 |     3122 | 3123 | 3124 |

    -------------------------------------------------------------------------------- /array-methods/find.js: -------------------------------------------------------------------------------- 1 | let movies = [ 2 | "Badrinath ki dulhaniya", 3 | "The amazing spider man", 4 | "Jatt james bond" 5 | ] 6 | const movie = movies.find(movie=>{ 7 | return movie.includes('Th') 8 | }) 9 | console.log(movie); -------------------------------------------------------------------------------- /array-methods/foreach.js: -------------------------------------------------------------------------------- 1 | const nums = [2,3,4,5,6,6]; 2 | nums.forEach((e)=>{ 3 | console.log(e); 4 | }) 5 | // add 2 in every element of the array 6 | let arr = [] 7 | nums.forEach((e)=>{ 8 | arr.push(e*2) 9 | }) 10 | console.log(arr) 11 | 12 | let cars = [ 13 | { 14 | "color": "purple", 15 | "type": "minivan", 16 | "registration": new Date('2017-01-03'), 17 | "capacity": 7 18 | }, 19 | { 20 | "color": "red", 21 | "type": "station wagon", 22 | "registration": new Date('2018-03-03'), 23 | "capacity": 5 24 | } 25 | ] 26 | cars.forEach((car)=>{ 27 | console.log(car.color); 28 | }) 29 | -------------------------------------------------------------------------------- /array-methods/map.js: -------------------------------------------------------------------------------- 1 | const arr = [12,3,5,6,7]; 2 | const newarr = arr.map((e)=>{ 3 | return e*2; 4 | }) 5 | console.log(newarr); 6 | const everOddArr = arr.map((n)=>{ 7 | return{ 8 | value: n, 9 | isEven: n%2===0 10 | } 11 | }) 12 | console.log(everOddArr); 13 | /* 14 | 15 | [ { value: 12, isEven: true }, 16 | { value: 3, isEven: false }, 17 | { value: 5, isEven: false }, 18 | { value: 6, isEven: true }, 19 | { value: 7, isEven: false } ] 20 | 21 | */ -------------------------------------------------------------------------------- /array-methods/reduce1.js: -------------------------------------------------------------------------------- 1 | const arr = [2,3,4,5]; 2 | // 5- [5,4,5] 3 | // 9- [9,5] 4 | // 14- 14 5 | 6 | const sum = arr.reduce((t,c)=>{ 7 | return t+c 8 | }) 9 | console.log(sum); -------------------------------------------------------------------------------- /array-methods/reduce2.js: -------------------------------------------------------------------------------- 1 | const max = (arr)=>{ 2 | return arr.reduce((max,curr)=>{ 3 | if(curr>max){ 4 | return curr; 5 | } 6 | return max; 7 | }) 8 | } 9 | console.log(max([12,23,5,64,23])) -------------------------------------------------------------------------------- /array-methods/reduce3.js: -------------------------------------------------------------------------------- 1 | const books = [{ 2 | title: 'Good Omens', 3 | authors: ['Terry Pratchett', 'Neil Gaiman'], 4 | rating: 4.25, 5 | genres: ['fiction', 'fantasy'] 6 | }, 7 | { 8 | title: 'Changing My Mind', 9 | authors: ['Zadie Smith'], 10 | rating: 3.83, 11 | genres: ['nonfiction', 'essays'] 12 | }, 13 | { 14 | title: 'Bone: The Complete Edition', 15 | authors: ['Jeff Smith'], 16 | rating: 4.42, 17 | genres: ['fiction', 'graphic novel', 'fantasy'] 18 | }, 19 | { 20 | title: 'American Gods', 21 | authors: ['Neil Gaiman'], 22 | rating: 4.11, 23 | genres: ['fiction', 'fantasy'] 24 | }, 25 | { 26 | title: 'A Gentleman in Moscow', 27 | authors: ['Amor Towles'], 28 | rating: 4.36, 29 | genres: ['fiction', 'historical fiction'] 30 | }, 31 | { 32 | title: 'The Name of the Wind', 33 | authors: ['Patrick Rothfuss'], 34 | rating: 4.54, 35 | genres: ['fiction', 'fantasy'] 36 | }, 37 | { 38 | title: 'The Overstory', 39 | authors: ['Richard Powers'], 40 | rating: 4.19, 41 | genres: ['fiction', 'short stories'] 42 | }, 43 | { 44 | title: 'A Truly Horrible Book', 45 | authors: ['Xavier Time'], 46 | rating: 2.18, 47 | genres: ['fiction', 'garbage'] 48 | }, 49 | { 50 | title: 'The Way of Kings', 51 | authors: ['Brandon Sanderson'], 52 | rating: 4.65, 53 | genres: ['fantasy', 'epic'] 54 | }, 55 | { 56 | title: 'Lord of the flies', 57 | authors: ['William Golding'], 58 | rating: 3.67, 59 | genres: ['fiction'] 60 | } 61 | ] 62 | 63 | const groupedByRatings = books.reduce((groupedBooks, book)=>{ 64 | let key = Math.floor(book.rating); 65 | if(!groupedBooks[key]){ 66 | groupedBooks[key]=[]; 67 | } 68 | groupedBooks[key].push(book); 69 | return groupedBooks; 70 | },{}) 71 | 72 | console.log(groupedByRatings) 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | // { 81 | // 2:[] 82 | // 3:[] 83 | // 4:[] 84 | // } -------------------------------------------------------------------------------- /arrays/concat.js: -------------------------------------------------------------------------------- 1 | let fruits = ['mango','grapes']; 2 | let groc = ['corn flakes','milk'] 3 | let shopList = fruits.concat(groc); 4 | let others = ['apple','coffee']; 5 | console.log(shopList); // ['mango','grapes','corn flakes','milk'] 6 | shopList = fruits.concat(groc,others); 7 | console.log(shopList); -------------------------------------------------------------------------------- /arrays/includes.js: -------------------------------------------------------------------------------- 1 | let ar = [1,2,3,5]; 2 | if(ar.includes(10)){ // false 3 | console.log(ar.indexOf(10)); 4 | } 5 | else{ 6 | console.log(ar.indexOf(2)); 7 | } 8 | // output - 1 -------------------------------------------------------------------------------- /arrays/join-reverse.js: -------------------------------------------------------------------------------- 1 | let arr = [1,2,3,4,5]; 2 | arr.reverse() 3 | console.log(arr); // [ 5, 4, 3, 2, 1 ] 4 | 5 | let names = ["Tushar","Rahul","Mohan"] 6 | let join1 = names.join() 7 | let join2 = names.join(' ') 8 | let join3 = names.join("&") 9 | console.log(join1) // Tushar,Rahul,Mohan 10 | console.log(join2) // Tushar Rahul Mohan 11 | console.log(join3) // Tushar&Rahul&Mohan -------------------------------------------------------------------------------- /arrays/pop.js: -------------------------------------------------------------------------------- 1 | let arr = [1,2,3,4,5,6] 2 | arr.push(7); 3 | console.log(arr); // [1, 2, 3, 4, 5, 6, 7 ] 4 | arr.pop(); 5 | console.log(arr) // [ 1, 2, 3, 4, 5, 6 ] -------------------------------------------------------------------------------- /arrays/shift.js: -------------------------------------------------------------------------------- 1 | let arr = [12,39,45] 2 | arr.shift() 3 | console.log(arr); // [ 39, 45 ] 4 | arr.unshift(12) 5 | console.log(arr); // [ 12, 39, 45 ] -------------------------------------------------------------------------------- /arrays/slice.js: -------------------------------------------------------------------------------- 1 | let watches = ['rolex','rado','apple','mi']; 2 | let expensiveWatches = watches.slice(0,2); 3 | console.log(expensiveWatches) // [ 'rolex', 'rado' ] 4 | let expensiveDigitalWatches = watches.slice(2); 5 | console.log(expensiveDigitalWatches) -------------------------------------------------------------------------------- /arrays/sort.js: -------------------------------------------------------------------------------- 1 | let arr = [1,24,54,6,3,53,3,55,65]; 2 | arr.sort() 3 | console.log(arr) -------------------------------------------------------------------------------- /arrays/splice.js: -------------------------------------------------------------------------------- 1 | let arr = [1,2,3,4,5,6]; 2 | // let arrDeletedItems = arr.splice(start[, deleteCount[, item1[, item2[, ...]]]]) 3 | arr.splice(1,0,15); 4 | console.log(arr); // [ 1, 15, 2, 3, 4, 5, 6 ] 5 | arr.splice(2,2); 6 | console.log(arr); // [1, 15, 4, 5, 6 ] -------------------------------------------------------------------------------- /async-await/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 |

    AXIOS DOCUMENT

    11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /async-await/script1.js: -------------------------------------------------------------------------------- 1 | console.log("Helo") 2 | 3 | // async function getData(){ 4 | // // if I want to request 3 urls 5 | // const res = await axios.get("https://pokeapi.co/api/v2/pokemon/1") 6 | // const res2 = await axios.get("https://pokeapi.co/api/v2/pokemon/2") 7 | // const res3 = await axios.get("https://pokeapi.co/api/v2/pokemon/3") 8 | // console.log(res.data) 9 | // } 10 | 11 | // async function getData(){ 12 | // // if I want to request 3 urls 13 | // const res = axios.get("https://pokeapi.co/api/v2/pokemon/1") 14 | // const res2 = axios.get("https://pokeapi.co/api/v2/pokemon/2") 15 | // const res3 = axios.get("https://pokeapi.co/api/v2/pokemon/3") 16 | // const poke1 = await res 17 | // const poke2 = await res2 18 | // const poke3 = await res3 19 | // // now res, res2, res3 are promises not data 20 | // console.log(poke1.data) 21 | // } 22 | 23 | 24 | async function getData(){ 25 | const res = axios.get("https://pokeapi.co/api/v2/pokemon/1") 26 | const res2 = axios.get("https://pokeapi.co/api/v2/pokemon/2") 27 | const res3 = axios.get("https://pokeapi.co/api/v2/pokemon/3") 28 | const results = await Promise.all([res,res2,res3]) 29 | console.log(results) 30 | } 31 | 32 | 33 | getData() 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | // async function hello(){ 44 | // return "Hey Guys" 45 | // } 46 | // hello().then((value) => { 47 | // console.log(value) 48 | // }) 49 | 50 | // const add = async (a,b) => { 51 | // if(typeof(a)!== 'number' | typeof(b)!== 'number' ){ 52 | // throw new Error("Not a number") 53 | // } 54 | // return a+b; 55 | // } 56 | 57 | // add(24,35).then((value) => {console.log(value)}) 58 | 59 | // async function getData(){ 60 | // try{ 61 | // const res = await axios.get('https://swapi.dev/api/planets') 62 | // console.log(res.data) 63 | // } 64 | // catch(err){ 65 | // console.log(err) 66 | // } 67 | // } 68 | 69 | 70 | // getData() 71 | 72 | // getData().catch((err) => {console.log(err)}) 73 | // --_________________________ 74 | 75 | // const moveX = (element, amount, delay) => { 76 | // return new Promise((resolve, reject) => { 77 | // setTimeout(() => { 78 | // const bodyBoundary = document.body.clientWidth; 79 | // const elRight = element.getBoundingClientRect().right; 80 | // const currLeft = element.getBoundingClientRect().left; 81 | // if (elRight + amount > bodyBoundary) { 82 | // reject({ bodyBoundary, elRight, amount }); 83 | // } 84 | // else { 85 | // element.style.transform = `translateX(${currLeft + amount}px)`; 86 | // resolve(); 87 | // } 88 | // }, delay); 89 | // }); 90 | // }; 91 | 92 | // const btn = document.querySelector('button'); 93 | // async function animateRight(el, amt) { 94 | // await moveX(el, amt, 1000); 95 | // await moveX(el, amt, 1000); 96 | // await moveX(el, amt, 1000); 97 | // await moveX(el, amt, 1000); 98 | // await moveX(el, amt, 1000); 99 | // await moveX(el, amt, 1000); 100 | // await moveX(el, amt, 1000); 101 | // await moveX(el, amt, 1000); 102 | // await moveX(el, amt, 1000); 103 | // await moveX(el, amt, 1000); 104 | // } 105 | // animateRight(btn, 100).catch((err) => { 106 | // console.log('Hit the right edge! Now Moving left!'); 107 | // animateRight(btn, -100); 108 | // }); 109 | 110 | // const btn = document.querySelector('button'); 111 | // moveX(btn, 100, 1000) 112 | // .then(() => moveX(btn, 100, 1000)) 113 | // .then(() => moveX(btn, 100, 1000)) 114 | // .then(() => moveX(btn, 100, 1000)) 115 | // .then(() => moveX(btn, 100, 1000)) 116 | // .then(() => moveX(btn, 100, 1000)) 117 | // .then(() => moveX(btn, 100, 1000)) 118 | // .then(() => moveX(btn, 100, 1000)) 119 | // .then(() => moveX(btn, 100, 1000)) 120 | // .then(() => moveX(btn, 100, 1000)) 121 | // .then(() => moveX(btn, 100, 1000)) 122 | // .then(() => moveX(btn, 100, 1000)) 123 | // .then(() => moveX(btn, 100, 1000)) 124 | // .then(() => moveX(btn, 100, 1000)) 125 | // .then(() => moveX(btn, 100, 1000)) 126 | // .then(() => moveX(btn, 100, 1000)) 127 | // .catch(({ bodyBoundary, amount, elRight }) => { 128 | // console.log(`Cannot Move! Body is ${bodyBoundary}px wide`); 129 | // console.log(`Element is at ${elRight}px, ${amount}px is too large!`); 130 | // }); 131 | 132 | //This function moves an element "amount" number of pixels after a delay. 133 | //If the element will stay on screen, we move the element and call the onSuccess callback function 134 | //If the element will move off screen, we do not move the element and instead call the onFailure callback 135 | // const moveX = (element, amount, delay, onSuccess, onFailure) => { 136 | // setTimeout(() => { 137 | // const bodyBoundary = document.body.clientWidth; 138 | // const elRight = element.getBoundingClientRect().right; 139 | // const currLeft = element.getBoundingClientRect().left; 140 | // if (elRight + amount > bodyBoundary) { 141 | // onFailure(); 142 | // } 143 | // else { 144 | // element.style.transform = `translateX(${currLeft + amount}px)`; 145 | // onSuccess(); 146 | // } 147 | // }, delay); 148 | // }; 149 | 150 | // LOOK AT THIS UGLY MESS! 151 | // moveX( 152 | // btn, 153 | // 300, 154 | // 1000, 155 | // () => { 156 | // //success callback 157 | // moveX( 158 | // btn, 159 | // 300, 160 | // 1000, 161 | // () => { 162 | // //success callback 163 | // moveX( 164 | // btn, 165 | // 300, 166 | // 1000, 167 | // () => { 168 | // //success callback 169 | // moveX( 170 | // btn, 171 | // 300, 172 | // 1000, 173 | // () => { 174 | // //success callback 175 | // moveX( 176 | // btn, 177 | // 300, 178 | // 1000, 179 | // () => { 180 | // //success callback 181 | // alert('YOU HAVE A WIDE SCREEN!'); 182 | // }, 183 | // () => { 184 | // //failure callback 185 | // alert('CANNOT MOVE FURTHER!'); 186 | // } 187 | // ); 188 | // }, 189 | // () => { 190 | // //failure callback 191 | // alert('CANNOT MOVE FURTHER!'); 192 | // } 193 | // ); 194 | // }, 195 | // () => { 196 | // //failure callback 197 | // alert('CANNOT MOVE FURTHER!'); 198 | // } 199 | // ); 200 | // }, 201 | // () => { 202 | // //failure callback 203 | // alert('CANNOT MOVE FURTHER!'); 204 | // } 205 | // ); 206 | // }, 207 | // () => { 208 | // //failure callback 209 | // alert('CANNOT MOVE FURTHER!'); 210 | // } 211 | // ); -------------------------------------------------------------------------------- /asynchronous-js/call-stack.js: -------------------------------------------------------------------------------- 1 | const repeat = (str, times) => { 2 | let result = ''; 3 | for (let i = 0; i < times; i++) 4 | { 5 | result += str; 6 | } 7 | return result; 8 | }; 9 | 10 | const scream = (str) => { 11 | return str.toUpperCase() + '!!!'; 12 | }; 13 | 14 | const getRantText = (phrase) => { 15 | let text = scream(phrase); 16 | let rant = repeat(text, 8); 17 | return rant; 18 | }; 19 | 20 | 21 | const makeRant = (phrase, el) => { 22 | const h1 = document.createElement('h1'); 23 | h1.innerText = getRantText(phrase); 24 | el.appendChild(h1); 25 | }; 26 | 27 | console.log('HELLO!'); 28 | 29 | makeRant('I hate mayonnaise', document.body); 30 | makeRant('if you have to cough, please cover your mouth', document.body); -------------------------------------------------------------------------------- /asynchronous-js/callbackhell.js: -------------------------------------------------------------------------------- 1 | const btn = document.querySelector('button'); 2 | 3 | // setTimeout(() => { 4 | // btn.style.transform = `translateX(100px)`; 5 | // setTimeout(() => { 6 | // btn.style.transform = `translateX(200px)`; 7 | // setTimeout(() => { 8 | // btn.style.transform = `translateX(100px)`; 9 | // setTimeout(() => { 10 | // btn.style.transform = `translateX(100px)` 11 | // }, 1000); 12 | // }, 1000); 13 | // }, 2000); 14 | // }, 3000); 15 | 16 | const moveX = (element,amount,delay, callback)=>{ 17 | setTimeout(() => { 18 | element.style.transform = `translateX(${amount}px)`; 19 | if(callback){ 20 | callback(); 21 | } 22 | }, delay); 23 | } 24 | 25 | moveX(btn,300,2000,()=>{ 26 | moveX(btn,200,1000) 27 | }) -------------------------------------------------------------------------------- /asynchronous-js/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /asynchronous-js/promises/chain.js: -------------------------------------------------------------------------------- 1 | const fakeRequest = (url) => { 2 | return new Promise((resolve, reject) => { 3 | setTimeout(() => { 4 | const pages = { 5 | '/users': [ 6 | { id: 1, username: 'Tushar' }, 7 | { id: 5, username: 'Rahul' } 8 | ], 9 | '/users/1': { 10 | id: 1, 11 | username: 'Tushar', 12 | country: 'India', 13 | work: 'Noida', 14 | role: 'Software Engineer', 15 | postid: 54 16 | }, 17 | '/users/5': { 18 | id: 5, 19 | username: 'Rahul', 20 | country: 'India', 21 | work: 'Noida', 22 | role: 'DevOps Engineer' 23 | }, 24 | '/posts/54': { 25 | id: 54, 26 | title: 'My new Post', 27 | 28 | }, 29 | '/about': "About page" 30 | } 31 | 32 | const data = pages[url] 33 | if (data) { 34 | resolve(pages[url]) 35 | } 36 | else { 37 | reject({ status: 400 }) 38 | } 39 | }, 2000) 40 | }) 41 | } 42 | 43 | // fakeRequest('/users').then((data)=>{ 44 | // let id = data[0].id; 45 | // fakeRequest(`/users/${id}`).then((data)=>{ 46 | // console.log(data) 47 | // }) 48 | 49 | // }) 50 | fakeRequest('/users').then((data) => { 51 | let id = data[0].id; 52 | return fakeRequest(`/users/${id}`) 53 | }) 54 | .then((data) => { 55 | // console.log(data) 56 | let postid = data.postid; 57 | return fakeRequest(`/posts/${postid}`) 58 | }) 59 | .then((data) => { 60 | console.log(data) 61 | }) 62 | .catch((err) => { console.log(err) }) -------------------------------------------------------------------------------- /asynchronous-js/promises/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /asynchronous-js/promises/promise-value.js: -------------------------------------------------------------------------------- 1 | const fakeRequest = (url)=>{ 2 | return new Promise((resolve,reject)=>{ 3 | setTimeout(()=>{ 4 | const pages = { 5 | '/users' : "Users pages", 6 | '/about' : "About page" 7 | } 8 | const data = pages[url] 9 | if(data){ 10 | 11 | resolve(pages[url]) 12 | } 13 | else{ 14 | reject({status:400}) 15 | } 16 | },2000) 17 | }) 18 | } 19 | 20 | fakeRequest().then((data)=>{ 21 | console.log(data) 22 | }).catch((res)=>{console.log(res.status)}) -------------------------------------------------------------------------------- /asynchronous-js/promises/script.js: -------------------------------------------------------------------------------- 1 | // const willGetYouDog = new Promise((resolve,reject)=>{ 2 | // const rand = Math.random(); 3 | // if(rand<0.5){ 4 | // resolve() 5 | // } 6 | // else 7 | // reject() 8 | // }) 9 | 10 | 11 | // willGetYouDog.then(()=>{ 12 | // console.log('DOGGGG') 13 | // }).catch((err)=>{console.log(err)}) 14 | const makeDogPromise = () => { 15 | return new Promise((resolve, reject) => { 16 | setTimeout(() => { 17 | const rand = Math.random(); 18 | if (rand < 0.5) { 19 | resolve() 20 | } 21 | else 22 | reject() 23 | }, 5000) 24 | }) 25 | } 26 | 27 | 28 | // willGetYouDog.then(() => { 29 | // console.log('DOGGGG') 30 | // }).catch((err) => { console.log(err) }) 31 | const pro = makeDogPromise() 32 | pro.then(()=>{ 33 | console.log("hello") 34 | }) 35 | -------------------------------------------------------------------------------- /dom/app.css: -------------------------------------------------------------------------------- 1 | h1 { 2 | color: purple; 3 | font-size: 60px; 4 | } 5 | 6 | #bear-photo { 7 | width: 250px; 8 | } 9 | 10 | .special { 11 | color: teal; 12 | font-size: 30px; 13 | border: 1px solid teal; 14 | } 15 | 16 | input[type="password"] { 17 | height: 50px; 18 | width: 100px; 19 | } 20 | .done{ 21 | color:gray; 22 | text-decoration: line-through; 23 | opacity: 50%; 24 | } -------------------------------------------------------------------------------- /dom/app.js: -------------------------------------------------------------------------------- 1 | // **************** 2 | // querySelector 3 | // **************** 4 | //To find the first li on the page: 5 | document.querySelector('li'); 6 | 7 | //To find the first element with class of special: 8 | document.querySelector('.special'); 9 | 10 | //To find the first element with id of main (there should only be one...) 11 | document.querySelector('#main'); 12 | 13 | // To find the first li with the class of special, nested inside of a ul, nested inside a section: 14 | document.querySelector('section ul li.special'); 15 | 16 | 17 | // **************** 18 | // querySelectorAll 19 | // **************** 20 | 21 | // To find ALL li's on the page: 22 | document.querySelectorAll('li'); 23 | 24 | // To find ALL elements with the class of special on the page: 25 | document.querySelectorAll('.special'); 26 | 27 | 28 | const newElement = (outer, inner, outerClass, innerClass, outerText, innerText)=>{ 29 | let e1 = document.createElement(outer) 30 | let e2 = document.createElement(inner) 31 | e1.className = outerClass; 32 | e2.className = innerClass; 33 | e2.innerText = innerText; 34 | e1.innerText = outerText; 35 | e1.appendChild(e2); 36 | return e1; 37 | } 38 | 39 | // let el = document.createElement("button"); 40 | // let e = document.createElement("li"); 41 | // e.className = "todo"; 42 | // e.appendChild(el) 43 | console.log(newElement("li","button",'todo','bt','any','X')) 44 | 45 | 46 | // manipulating class 47 | // const todo = document.querySelector('#todos .todo') 48 | const todos = document.querySelector("#todos") 49 | const todoInput = document.querySelector(".todoinput") 50 | const todoAdd = document.querySelector(".todoadd"); 51 | todoAdd.addEventListener("click",()=>{ 52 | let value = todoInput.value; 53 | // let node = document.createElement("li"); 54 | // let textnode = document.createTextNode() 55 | let newCreatedElement = newElement("li","button",'todo','bt',value,'X') 56 | todos.appendChild(newCreatedElement) 57 | // todos.innerHTML+= `
  • ${value}
  • `; 58 | }) 59 | 60 | let buttonTodo = document.querySelectorAll("#todos .todo button") 61 | buttonTodo.forEach((e)=>{ 62 | e.addEventListener("click",()=>{ 63 | let todo = e.parentElement; 64 | todo.setAttribute("class","done") 65 | }) 66 | }) 67 | 68 | // todo.style.color = 'gray'; 69 | // todo.style.textDecoration = 'line-through'; 70 | // todo.style.opacity = '50%'; -------------------------------------------------------------------------------- /dom/create-elements.js: -------------------------------------------------------------------------------- 1 | const url = 'https://cdn.vox-cdn.com/thumbor/FxBr6MiQn3W2bWPBA1dQqLvNREQ=/0x0:2040x1360/920x613/filters:focal(857x517:1183x843):format(webp)/cdn.vox-cdn.com/uploads/chorus_image/image/61520649/jbareham_180424_2499_0007.0.jpg' 2 | const section = document.querySelector('section') 3 | const newImg = document.createElement('img') 4 | newImg.setAttribute('src',url) 5 | section.appendChild(newImg) 6 | -------------------------------------------------------------------------------- /dom/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | querySelector 9 | 10 | 11 | 12 | 13 | 14 |

    My Webpage

    15 |

    Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas sint natus nostrum quas laudantium quasi ut 16 | voluptatem fugiat aliquid architecto. In distinctio expedita doloribus veritatis, vitae voluptates optio commodi 17 | itaque. 18 | Hell 19 |

    20 |

    Lorem ipsum dolor sit amet consectetur adipisicing elit. Doloribus sint, magni dolorum sapiente voluptate 21 | quia 22 | praesentium autem! Veniam delectus, placeat excepturi in porro minima quo laudantium temporibus, aliquid repellendus 23 | similique. 24 |

    25 |
    26 | 27 | 28 | 29 |
    30 |

    31 | ADIJAKLSJDLKSAJLDKJL 32 |

    33 | 38 | 41 |
    42 | 47 |
    48 |
    49 | 50 | 56 |
    57 |

    TODO List

    58 | 59 | 60 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /dom/insert.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tush-tr/learn-lang-javascript/515acb7e3606aa34182a1150893784d12dc412f5/dom/insert.js -------------------------------------------------------------------------------- /dom/remove.js: -------------------------------------------------------------------------------- 1 | const ul = document.querySelector('ul')​ 2 | const removeMe = ul.querySelector('.special')​ 3 | ul.removeChild(removeMe) 4 | -------------------------------------------------------------------------------- /functions/average.js: -------------------------------------------------------------------------------- 1 | // write a function to find the average value in an array of numbers. 2 | // avg([0,50]) // 25 3 | function avg(arr){ 4 | const l = arr.length; 5 | // for(let i =0;i{ 9 | return total+num; 10 | }) 11 | return sum/l; 12 | } 13 | console.log(avg([0,50])); 14 | -------------------------------------------------------------------------------- /functions/diceroll.js: -------------------------------------------------------------------------------- 1 | function diceRoll(){ 2 | let roll = Math.floor(Math.random()*6)+1; 3 | console.log(roll); 4 | } 5 | -------------------------------------------------------------------------------- /functions/funcargs.js: -------------------------------------------------------------------------------- 1 | function callTwice(func){ 2 | func(); 3 | func(); 4 | } 5 | 6 | function laugh(){ 7 | console.log("hahahahahhah"); 8 | } 9 | 10 | callTwice(laugh); -------------------------------------------------------------------------------- /functions/getcard.js: -------------------------------------------------------------------------------- 1 | /* 2 | write a getCard() function which returns a random playing card object, like 3 | { 4 | value: 'K', 5 | suit: 'clubs' 6 | } 7 | pick a random value from 8 | -- 1,2,3,4,5,6,7,8,9,10,J,Q,K,A 9 | pick a random quit from 10 | clubs, spades, hearts, diamonds 11 | return both in an object 12 | */ 13 | function getCard(){ 14 | let value; 15 | let randNum = Math.floor(Math.random()*14)+1; 16 | if(randNum===11){ 17 | value = 'J'; 18 | } 19 | else if(randNum===12){ 20 | value = 'Q'; 21 | } 22 | else if(randNum===13){ 23 | value = 'K'; 24 | } 25 | else if(randNum===14){ 26 | value = 'A'; 27 | } 28 | else{ 29 | value = randNum; 30 | } 31 | let suit; 32 | let randSuit = Math.floor(Math.random()*4)+1; 33 | switch(randSuit){ 34 | case 1: 35 | suit= 'clubs'; 36 | break; 37 | case 2: 38 | suit = 'spades'; 39 | break; 40 | case 3: 41 | suit = 'hearts'; 42 | break; 43 | case 4: 44 | suit = 'diamonds'; 45 | break; 46 | } 47 | return {value: value,suit: suit} 48 | } 49 | console.log(getCard()) -------------------------------------------------------------------------------- /functions/higherorder.js: -------------------------------------------------------------------------------- 1 | function add(x,y){ 2 | return x+y; 3 | } 4 | const subtract = function(x,y){ 5 | return x-y; 6 | } 7 | 8 | function multiply(x,y){ 9 | return x*y; 10 | } 11 | const divide = function(x,y){ 12 | return x/y; 13 | } 14 | // let's add all these functions to an array 15 | const operations = [add,subtract,multiply,divide]; 16 | // now we can use this array of functions like this: 17 | // console.log(operations[0](3,4)) //7 18 | for(let func of operations){ 19 | console.log(func(12,34)); 20 | } 21 | // now I can also add these functions into an object and create a method 22 | const thing = { 23 | doSomething: multiply 24 | } 25 | // now I can call and use this function as a method of object 26 | console.log(thing.doSomething(23,3)); 27 | 28 | 29 | -------------------------------------------------------------------------------- /functions/makebetween.js: -------------------------------------------------------------------------------- 1 | function makeBetweenFunc(min,max){ 2 | return function (val){ 3 | return val>=min && val<=max; 4 | } 5 | } 6 | const inAgeRange = makeBetweenFunc(18,100); 7 | console.log(inAgeRange(45)); -------------------------------------------------------------------------------- /functions/operations.js: -------------------------------------------------------------------------------- 1 | function add(x,y){ 2 | return x+y; 3 | } 4 | const subtract = function(x,y){ 5 | return x-y; 6 | } 7 | function multiply(x,y){ 8 | return x*y; 9 | } 10 | const divide = function(x,y){ 11 | return x/y; 12 | } 13 | function operations(oper,x,y){ 14 | return oper(x,y); 15 | } 16 | console.log(operations(add,2,3)); // 5 17 | console.log(operations((a,b)=>{ 18 | return a+b; 19 | },45,5)); // 50 20 | 21 | -------------------------------------------------------------------------------- /functions/pangram.js: -------------------------------------------------------------------------------- 1 | /* 2 | a pangram is a sentence that contains every letter of the alphabet, 3 | write a function called isPangram, which checks to see if a given sentence contains every letter of the alphabet. 4 | */ 5 | function isPangram(sentence){ 6 | sentence = sentence.toLowerCase(); 7 | for(let char of 'abcdefghijklmnopqrstuvwxyz'){ 8 | if(sentence.indexOf(char)===-1){ 9 | return false; 10 | } 11 | } 12 | return true; 13 | } 14 | console.log(isPangram('Sphinx of black quartz, judge my vow.')) -------------------------------------------------------------------------------- /functions/passwordvalidator.js: -------------------------------------------------------------------------------- 1 | /* 2 | write a isValidPassword function. 3 | accepts two arguments: password and username 4 | password must: 5 | - be at least 8 characters 6 | - can't contain spaces 7 | - can't contain the username 8 | if all requirements are met, return true, otherwise false 9 | 10 | isValidPassword('89Fjjlnms','dogluvr'); // true 11 | */ 12 | 13 | function isValidPassword(password, username){ 14 | const tooShort = password.length<8; 15 | const containspace = password.indexOf(' ')!==-1; 16 | const containusername = password.indexOf(username)!== -1; 17 | if(tooShort || containspace || containusername){ 18 | return false; 19 | } 20 | return true; 21 | } 22 | 23 | -------------------------------------------------------------------------------- /functions/returnfunc.js: -------------------------------------------------------------------------------- 1 | function multiplyBy(num){ 2 | return function(a){ // anonymous function 3 | return a*num; 4 | 5 | } 6 | } 7 | const triple = multiplyBy(3); 8 | console.log(triple(20)); // 60 9 | console.log(multiplyBy(3)(20)); // 60 -------------------------------------------------------------------------------- /http-requests/axios/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 |

    AXIOS DOCUMENT

    11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /http-requests/axios/script.js: -------------------------------------------------------------------------------- 1 | const url = 'https://swapi.dev/api/planets' 2 | 3 | const showData = ({data})=>{ 4 | data.results.forEach((planet) => { 5 | console.log(planet.name) 6 | }) 7 | return axios.get(data.next) 8 | } 9 | 10 | axios.get(url) 11 | .then(showData) 12 | .then(showData) 13 | 14 | // axios.get(data.next).then(({ data }) => { 15 | // data.results.forEach((planet) => { console.log(planet.name) }) 16 | // axios.get(data.next).then(({ data }) => { 17 | // data.results.forEach((planet) => { console.log(planet.name) }) 18 | 19 | // }) 20 | // }) -------------------------------------------------------------------------------- /http-requests/axios/script2.js: -------------------------------------------------------------------------------- 1 | async function getData() { 2 | try { 3 | const response = await axios.get('https://swapi.dev/api/planets'); 4 | console.log(response); 5 | } catch (error) { 6 | console.error(error); 7 | } 8 | } 9 | getData(); -------------------------------------------------------------------------------- /http-requests/fetch/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /http-requests/fetch/script.js: -------------------------------------------------------------------------------- 1 | const url = "https://swapi.dev/api/planets"; 2 | 3 | const checkStatusAndParse = (response)=>{ 4 | if(!response.ok) throw new Error('Status code error') 5 | return response.json(); 6 | } 7 | const printPlanets = (data)=>{ 8 | console.log("FETCHED ALL PLANETS") 9 | data.results.forEach((planet)=>{ 10 | console.log(planet.name) 11 | }) 12 | return Promise.resolve(data.next) 13 | } 14 | 15 | const fetchMorePlanets = (url)=>{ 16 | return fetch(url); 17 | } 18 | 19 | fetch(url) 20 | .then(checkStatusAndParse) 21 | .then(printPlanets) 22 | .then(fetchMorePlanets) 23 | .then(checkStatusAndParse) 24 | .then(printPlanets) 25 | .then(fetchMorePlanets) 26 | .then(checkStatusAndParse) 27 | .then(printPlanets) 28 | .catch((err)=>{console.log(err)}) 29 | 30 | -------------------------------------------------------------------------------- /http-requests/xml-http/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /http-requests/xml-http/script.js: -------------------------------------------------------------------------------- 1 | // function reqListener () { 2 | // console.log(this.responseText); 3 | // } 4 | 5 | // var oReq = new XMLHttpRequest(); 6 | // oReq.addEventListener("load", reqListener); 7 | // oReq.open("GET", "http://www.example.org/example.txt"); 8 | // oReq.send(); 9 | 10 | const url = "https://swapi.dev/api/planets" 11 | const myReq = new XMLHttpRequest(); 12 | myReq.addEventListener('load', ()=>{ 13 | console.log("it works") 14 | }); 15 | myReq.addEventListener('error', ()=>{ 16 | console.log("Error") 17 | }); 18 | myReq.open('GET',url,true); 19 | myReq.send(); 20 | console.log("Request sent") 21 | console.log(myReq.response) -------------------------------------------------------------------------------- /ifelse/prob1.js: -------------------------------------------------------------------------------- 1 | function evenOdd(num) { 2 | if (num % 2 === 0) { 3 | console.log("Even") 4 | } 5 | else{ 6 | console.log("odd") 7 | } 8 | } 9 | evenOdd(2); 10 | evenOdd(5); -------------------------------------------------------------------------------- /ifelse/prob2.js: -------------------------------------------------------------------------------- 1 | function findMax(n1,n2){ 2 | if(n1n2){ 3 | if(n3>n1){ 4 | console.log(`${n3} is max`); 5 | } 6 | else{ 7 | console.log(`${n1} is max`); 8 | } 9 | } 10 | else{ 11 | if(n3>n2){ 12 | console.log(`${n3} is max`); 13 | } 14 | else{ 15 | console.log(`${n2} is max`) 16 | } 17 | } 18 | } 19 | 20 | findMax(23,45,24); -------------------------------------------------------------------------------- /ifelse/prob4.js: -------------------------------------------------------------------------------- 1 | function isVowel(al){ 2 | if(al==="a" || al=== "e" || al==="i" || al==="o" || al==="u" || al==="A" || al=== "E" || al==="I" || al==="O" || al==="U"){ 3 | console.log("vowel"); 4 | } 5 | else{ 6 | console.log("constant"); 7 | } 8 | } 9 | isVowel("a"); 10 | isVowel("R"); -------------------------------------------------------------------------------- /javascript-code/README.md: -------------------------------------------------------------------------------- 1 |
  • 2 |
  • 3 |
  • 4 |
  • 5 |
  • 6 |
  • 7 |
  • 8 |
  • -------------------------------------------------------------------------------- /javascript-code/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /javascript-code/storage.js: -------------------------------------------------------------------------------- 1 | localStorage.setItem('name','Tushar') 2 | localStorage.setItem('name2', "Rahul") 3 | 4 | let nam = localStorage.getItem('name') 5 | console.log(nam) 6 | 7 | // clear all the local storage 8 | // localStorage.clear() 9 | 10 | localStorage.removeItem('name') 11 | 12 | const arr = ["bhindi","pyaj","Nimbu"]; 13 | localStorage.setItem('Sabzi', JSON.stringify(arr)) 14 | 15 | 16 | // ##### Session Storage #### 17 | sessionStorage.setItem('students',JSON.stringify(['Tushar',"Rahul"])) 18 | -------------------------------------------------------------------------------- /loops/gameboard.js: -------------------------------------------------------------------------------- 1 | const gameBoard = [ 2 | [4,32,8,4], 3 | [64,8,32,2], 4 | [8,32,16,4], 5 | [2,8,4,2] 6 | ]; 7 | for(let i=0;i < gameBoard.length;i++){ 8 | // console.log(gameBoard[i]); 9 | for(let j=0;j{ 2 | return Math.floor(Math.random()*a)+1; 3 | } 4 | let target = randNum(10); 5 | let guess = randNum(10); 6 | while(guess!==target){ 7 | console.log(`guess is ${guess} Trying again.....`) 8 | guess = randNum(10); 9 | } 10 | console.log(`Congrats guess ${guess} was right`); -------------------------------------------------------------------------------- /object-methods/anno.js: -------------------------------------------------------------------------------- 1 | const annoyer = { 2 | phrases: [ 3 | "The best of both worlds", 'Speak of the devil','See eye to eye','Once in a blue moon', 4 | 'when pigs fly' 5 | ], 6 | pickPhrase(){ 7 | const {phrases} = this; 8 | const idx = Math.floor(Math.random() * phrases.length); 9 | return phrases[idx] 10 | }, 11 | start(){ 12 | const pickedPhrase = this.pickPhrase(); 13 | setInterval(()=>{ 14 | console.log(pickedPhrase); 15 | console.log(this.pickPhrase())// only work with arrow function 16 | },3000) 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /object-methods/deckofcards.js: -------------------------------------------------------------------------------- 1 | function makeDeck() { 2 | const deck = [] 3 | const suits = ['hearts', 'diamonds', 'spades', 'clubs']; 4 | const values = '1,2,3,4,5,6,7,8,9,10,J,Q,K,A'; 5 | for(let value of values.split(',')){ 6 | for(let suit of suits){ 7 | deck.push({value,suit}) 8 | } 9 | } 10 | return deck; 11 | } 12 | 13 | function drawCard(deck){ 14 | return deck.pop() 15 | } 16 | 17 | 18 | const myDeck = makeDeck(); 19 | const card1 = drawCard(myDeck); 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | // makeDeck(){ 31 | // [ 32 | // {value: '5',suit:'hearts'} 33 | // ] 34 | // } -------------------------------------------------------------------------------- /object-methods/thiskw.js: -------------------------------------------------------------------------------- 1 | function sayHi(){ 2 | console.log("Hii") 3 | // this refers to the window (global scope object in the browser) 4 | console.log(this) 5 | } 6 | 7 | 8 | const person = { 9 | first: "Tushar", 10 | last : "Rajpoot", 11 | nickName: false, 12 | fullName(){ 13 | // console.log(this) 14 | return `${this.first} ${this.last}` 15 | }, 16 | printBio(){ 17 | const fullName = this.fullName(); 18 | console.log(`${fullName} is a person`) 19 | }, 20 | laugh: ()=>{ 21 | console.log(this); 22 | console.log(this.nickName) 23 | }// arrow functions don't behave that way 24 | // this refers to window object not current object 25 | } 26 | 27 | console.log(person.fullName()) 28 | // now this refers to person object 29 | 30 | person.printBio(); 31 | 32 | 33 | -------------------------------------------------------------------------------- /oops/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | OOPS 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /oops/script.js: -------------------------------------------------------------------------------- 1 | // console.log("Hello") 2 | // String.prototype.getup = function(){ 3 | // return this.toUpperCase() 4 | // } 5 | // Array.prototype.pop = function(){ 6 | // return "Sorry" 7 | // } 8 | // console.log("Tushar".getup()) 9 | // console.log([2,3,4].pop()) 10 | 11 | // const navColor = new Color('pink',[345,354,645]) 12 | // const logoColor = new Color('green',[255,255,255]) 13 | // function hex(r,g,b){ 14 | // return '#' + ((1 << 24) + (r << 16 ) + (g << 8) + b).toString(16).slice(1) 15 | 16 | // } 17 | 18 | // function rgb(r,g,b){ 19 | // return `rgb(${r}, ${b}, ${g})`; 20 | // } 21 | 22 | 23 | // function makeColor(r, g, b) { 24 | // const color = {} 25 | // color.r = r; 26 | // color.g = g; 27 | // color.b = b; 28 | // color.rgb = function () { 29 | // const { r, g, b } = this; 30 | // return `rgb(${r}, ${b}, ${g})` 31 | // } 32 | // color.hex = function () { 33 | // const { r, g, b } = this; 34 | // return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1) 35 | 36 | // } 37 | // return color; 38 | // } 39 | 40 | // const c = makeColor(23, 23, 334) 41 | 42 | // function Car(make,model,year){ 43 | // this.make = make 44 | // this.model = model 45 | // this.year = year 46 | // } 47 | 48 | // Car.prototype.carPrice = function(){ 49 | // const {make,year,model} = this; 50 | // return `Price(${make},${year},${model})` 51 | // } 52 | // let car1 = new Car("Audi", "Q7", "2022") 53 | 54 | // class Color{ 55 | // constructor(r,g,b){ 56 | // this.r = r 57 | // this.g = g 58 | // this.b = b 59 | // } 60 | // greet(){ 61 | // const {r,g,b} = this 62 | // return `rgb(${r}, ${g}, ${b})` 63 | // } 64 | // } 65 | 66 | // const c1 = new Color(333,43,34) 67 | 68 | class Pet { 69 | constructor(name,age){ 70 | this.name = name 71 | this.age = age 72 | } 73 | eat(){ 74 | return `${this.name} is eating` 75 | } 76 | } 77 | 78 | class Cat extends Pet{ 79 | meow(){ 80 | return "MEOWWW" 81 | } 82 | } 83 | 84 | class Dog extends Pet{ 85 | bark(){ 86 | return "BARKWW" 87 | } 88 | } 89 | 90 | const cat1 = new Cat("Losi",5) 91 | const dog1 = new Dog("Rockie",7) --------------------------------------------------------------------------------