Asfaq

Javascript Basics

Sep 24th, 2023
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 45.73 KB | None | 0 0
  1. // document.write('hello');
  2. // alert('hello');
  3. // console.log('hello');
  4.  
  5. // document.write({name: 'john'});
  6. // alert({name: 'john' });
  7. // console.log({name: 'john'});
  8. // ------------------------------------------
  9. // ----------------------------------------
  10. // Variable - store, access, Modify === Value
  11. // Declare, Assignment, Operator, Assign value
  12. // -----------------------------------------------
  13. // let name = "John";
  14. // let address, zip, state;
  15. // address = "101 main street";
  16. // console.log(address);
  17.  
  18. // ###### ------------------------------------------------
  19. // let vs var vs const(CONSTANT) - can't re-assign
  20. // ---- using var
  21. // var value1 = "some value";
  22. // value1 = "some other value";
  23. // console.log(value1);
  24.  
  25. // ---- using let
  26. // let value2 = "John";
  27. // value2 = "Peter";
  28. // console.log(value2);
  29.  
  30. // ------- using const
  31. // const value3 = "Jordan";
  32. // value3 = "Abraham"; // Assignment to constant variable.
  33. // console.log(value3);
  34. // const value3; /* Missing initializer */
  35.  
  36. // #### ------- Cotation ------' ' , " " -----------------
  37. // const name = 'john\'s courses are the best';
  38. // const name = "john's courses are the best";
  39. // console.log(name);
  40.  
  41. // ---------- String concatenation
  42. // ` ` - backticks(template strings) easier option
  43. //--------------------------
  44. // const name = 'john';
  45. // const lastname = 'shakeandbake';
  46. // let fullname = name + ' ' + lastname;
  47. // console.log('Hello there your fullname is: ' + fullname);
  48. //-----------------------------
  49. // const website = 'google';
  50. // const url = 'https://www.' + website + '.com';
  51. // console.log(url);
  52.  
  53. //------------ Numbers --------------
  54. // Loosely typed = don't declare type
  55. // const number = 34;
  56. // let pants = 2.4455;
  57. // pants = 'are great';
  58. // const number2 = 2.456;
  59. // const number3 = '2.345';
  60.  
  61. // const add = number + number2;
  62. // const sub = number - number2;
  63. // const mult = number * number2;
  64. // const div = number / number2;
  65.  
  66. // console.log(add);
  67. // console.log(sub);
  68. // console.log(mult);
  69. // console.log(div);
  70.  
  71. // ---------------- Numbers -------------------
  72. // +=, -=, /=, *=, ++, -- , %
  73. // Modulas (%) operator returns the ramainder after integer division
  74.  
  75. // let number = 40;
  76. // number += 5;
  77. // number += 5;
  78. // number ++;
  79. // number --;
  80. // console.log(number);
  81.  
  82. // ------ Modulus ----------------------------------------
  83. // const slices = 10;
  84. // const children = 4;
  85. // const amount = slices % children;
  86.  
  87. // const random = 4 + 5 + 10 * 10;
  88. // const random2 = (4 + 5 + 10) * 10;
  89. // console.log(random);
  90. // console.log(random2);
  91. // console.log(amount);
  92.  
  93. // ------------ Implicit Type conversion ---------------
  94. // const name = 'john';
  95. // const lastname = 'jordan';
  96. // const fullname = name + ' ' + lastname;
  97. // console.log(fullname);
  98.  
  99. // const number = 4;
  100. // const number2 = 10;
  101. // const result = number + number2;
  102. // console.log(result);
  103.  
  104. // const value = name - lastname;
  105. // console.log(value); /* NaN = Not a Number */
  106.  
  107. // ------------------------------------------
  108. // let number3 = 10 /* '10' */;
  109. // let number4 = '23';
  110.  
  111. // let number3 = 10;
  112. // let number4 = 23;
  113. // number4 = '23'; /* Details in DOM Module */
  114. // ------------------------------------------
  115. // const result2 = number3 + number4;
  116. /*
  117. With [+] operator it makes all the difference..
  118. */
  119. // console.log(result2);
  120. // -------------------------------------------
  121.  
  122. /*
  123. In console, the blue color is type-defined. If it is in
  124. black color it is a string.
  125. */
  126. // -------------------------------------------
  127. // const randomNumber = 13;
  128. // input - type="number" id="amount"
  129. // button type="submit"
  130. // document.querySelector('.form').addEventListener('submit',
  131. // function(e){
  132. // e.preventDefault();
  133. // let value = document.getElementById('amount').value;
  134. // value = parseInt(value);
  135. // console.log('Input value type');
  136. // console.log(value);
  137. // console.log('Sum of two values');
  138. // console.log(randomNumber + value);
  139. // });
  140.  
  141. // -------------------------------------------------------
  142.  
  143. // typeof - operator (typeof variable) (typeof value)
  144.  
  145.  
  146. // String
  147. // const text = 'some text';
  148. // console.log(typeof text);
  149. // console.log(typeof 'some text');
  150.  
  151. // Number
  152. // const number = 45;
  153. // console.log(typeof number);
  154.  
  155. // Boolean
  156. // let value1 = true;
  157. // let value2 = false;
  158. // console.log(typeof value1);
  159.  
  160. // Null
  161. /*
  162. Here in JS has a bug. null is not an object
  163. But null is null.
  164. -- Read about Null and Undefined
  165.  
  166. */
  167. // const result = null;
  168. // console.log(typeof result);
  169. // console.log(typeof null);
  170.  
  171. // Undefined - Nothing is inside a variable
  172. // let name;
  173. // console.log(name);
  174.  
  175. // Symbol (ES6)
  176. // -----------------------------------
  177.  
  178. // -----------------------------------
  179. // Arrays, Functions and Objects
  180. // -----------------------------------
  181.  
  182. // Arrays - [], 0 index based
  183. // const friend1 = 'anna';
  184. // const friend2 = 'anna';
  185. // const friend3 = 'anna';
  186. // const friend4 = 'anna';
  187.  
  188. // const friends = ['john','bob', 45, undefined,null];
  189.  
  190. // let bestfriend = friends[0];
  191.  
  192. // console.log(bestfriend);
  193. // --------------------------------------
  194.  
  195. // Functions Basics [ {Declare} and then {Invoke} ]
  196.  
  197.  
  198. // function hello(){
  199. // console.log('Hello there Bob');
  200. // console.log('Hello there John');
  201. // console.log('Hello there Susy');
  202. // }
  203.  
  204. // hello(); /* Invoking here */
  205.  
  206.  
  207. // come code here...
  208.  
  209. // come code here...
  210.  
  211. // come code here...
  212.  
  213. // ------------------------------------------------
  214. // Arrays, Functions and Objects
  215. // params - when declare/define [placeholders, local vars]
  216. // arguments - when [invoke/call/run]
  217. // use vars/values, multiple params, undefined
  218.  
  219. // ---------------------------------------------
  220. // function helloBob(){
  221. // console.log('Hello there Bob');
  222. // }
  223.  
  224. // function helloAnna(){
  225. // console.log('Hello there Anna');
  226. // }
  227.  
  228. // function helloSusy(){
  229. // console.log('Hello there Susy');
  230. // }
  231.  
  232. // helloBob();
  233. // helloAnna();
  234. // helloSusy();
  235. // ---------------------------------------------
  236. // const bob = 'Bob';
  237. // const susy = 'Susy';
  238. // const anna = 'Anna';
  239.  
  240.  
  241. // // local variables
  242. // function greet(name,second){
  243. // console.log(second);
  244. // console.log('Hello there ' + name);
  245. // }
  246. // // console.log(name); // gives mirror image
  247.  
  248. // greet(4); // number can also sent
  249. // greet(bob);
  250. // greet(anna,'Susy');
  251. // greet(susy);
  252. // ------------------------------------------------
  253. // Arrays, Functions and Objects
  254. // return
  255. // default undefined, shortcuts,ignores after [return]
  256. // 1 inch = 2.54 cm
  257. // const wallHeight = 80;
  258. // function calculate(value){
  259. // -----------------------------------------
  260. // console.log('The value is: ' + value * 2.54 + ' cm');
  261. // return 'hello world';
  262. // -----------------------------------------
  263. // const newValue = value * 2.54;
  264. // return newValue;
  265. // }
  266.  
  267. // const width = calculate(100);
  268. // const height = calculate(wallHeight);
  269.  
  270. // const dimensions = [width,height];
  271. // console.log(dimensions);
  272.  
  273. // --------------------------------------------------
  274. // Expressions - Another way define
  275. // Create a variable, assign to FUNCTION(not value), user var
  276. // diff - hoisting, use - arrow func, libraries,
  277.  
  278. // function definition/declaration
  279. // function addValues(num1, num2){
  280. // return num1+num2;
  281. // }
  282. // const firstValue = addValues(3,4);
  283. // const secondValue = addValues(12,34);
  284.  
  285. // function expression
  286. // const add = function (num1, num2){
  287. // does not have name
  288. // this is called anonymous function
  289. // return num1+num2;
  290. // };
  291. // const thirdValue = add(5,6);
  292. // in array we can store all kinds of values.
  293. // const values = [firstValue, secondValue, thirdValue];
  294. // console.log(values);
  295. // -----------------------------
  296. // Arrow Functions
  297. // const multiply = (num1, num2) => num1 * num2;
  298. // ----------------------------------------------
  299. // Arrays, Functions and Objects
  300. // Objects - key/value pairs methods
  301. // dot notation
  302.  
  303. // const person = {
  304. // name: 'john',
  305. // lastName: 'peters',
  306. // age: 40,
  307. // education: false,
  308. // married: true,
  309. // siblings:['anna','susan','peter'],
  310. // greeting: function (){
  311. // console.log('Hello my name is John');
  312. // }
  313. // }
  314. // const age = person.age;
  315. // console.log(age);
  316. // person.name = 'bob';
  317. // console.log(person.name);
  318. // console.log(person.siblings[2]);
  319. // person.greeting();
  320.  
  321. // ------------------------------------------------
  322. // Conditional Statements
  323. // Comparison Operators
  324. // >,<,>=,<=,==,===,!=,!==
  325. // else if and !
  326. // == checks only value
  327. // === checks value and type
  328. // const num1 = 6;
  329. // const num2 = '6';
  330. // const num2 = 10;
  331.  
  332. // const result = num1 >= num2;
  333. // -------------------------------------
  334. // const value = false;
  335. // if(!value){
  336. // console.log('value is false');
  337. // }
  338. // -------------------------------------------------
  339. // if(num1 > num2){
  340. // console.log('first number is bigger than second');
  341. // } else if(result) {
  342. // console.log('first number equal to a second');
  343. // } else {
  344. // console.log('second number is bigger than first');
  345. // }
  346. // -------------------------------------
  347. // const value = num1 == num2;
  348. // const value2 = num1 === num2;
  349. // const value = num1 != num2;
  350. // const value2 = num1 !== num2;
  351. // console.log(value);
  352. // console.log(value2);
  353.  
  354. // -------------------------------------------------
  355. // Logical Operators
  356. // || - OR , && - AND, !
  357. // const name = 'bob';
  358. // const age = 26;
  359. // if(name === 'bob' && age === 24){
  360. // console.log('hello there user');
  361. // } else {
  362. // console.log('wrong values');
  363. // }
  364.  
  365. // ----------------------------------------
  366. // Switch - if else
  367. // dice values - 1-6
  368.  
  369. // const dice = 3;
  370. // switch(dice){
  371. // case 1:
  372. // console.log('you got one');
  373. // break;
  374. // case 2:
  375. // console.log('you got two');
  376. // break;
  377. // case 3:
  378. // console.log('you got three');
  379. // break;
  380. // default:
  381. // console.log('you did not roll the dice');
  382. // }
  383. // -------------------------------------------------
  384. // Loops
  385. // repeatedly run a block of code while conditon is true
  386. // -----------------------------------------------------
  387. // while loop
  388. // let /*const*/ amount = 10;
  389. // while(amount > 0){
  390. // console.log('I have ' + amount + ` dollars and I'm going
  391. // to the mall`);
  392. // amount--;
  393. // /* Uncaught TypeError: Assignment to constant variable.*/
  394. // }
  395.  
  396. // -----------------------------------------------------
  397. // do-while loop
  398. // code block first, condition second
  399. // runs at least
  400.  
  401. // let money = 0;
  402. // do{
  403. // console.log('You have ' + money + ' dollars');
  404. // money++;
  405. // } while(money< 10);
  406.  
  407. // -----------------------------------------------------
  408. // for loop
  409. // let i;
  410. // for(i=0; i<10; i++){
  411. // console.log('and the number is: ' + i);
  412. // }
  413. // -------------------------------------------------
  414. // ===================================================
  415. /*----------------- PART 2 -------------------------*/
  416. // ===================================================
  417. // Connecting the Dots
  418. // String Methods
  419. // Global/ Local scope
  420. // Array Iterators - (map, filter, reduce)
  421. // Global Objects - Math, Date
  422. // -------------------------------------------------
  423. // String properties and methods
  424. // wrapper String Object, don't memorize methods
  425. // ----------------------------------------------
  426. // let text = 'Peter Jordan';
  427.  
  428. // const person = {
  429. // name: 'peter', // property
  430. // greeting(){
  431. // method
  432. // console.log("Hey, I'm Peter");
  433. // },
  434. // };
  435. // console.log(person);
  436. // console.log(person.name);
  437. // person.greeting();
  438. // ----------------------------------------------
  439. // let text = ' Peter Jordan';
  440. // let result = text.length;
  441. // console.log(result);
  442. // console.log(text.toLowerCase());
  443. // console.log(text.toUpperCase());
  444. // console.log(text.charAt(0));
  445. // console.log(text.charAt(1));
  446. // console.log(text.charAt(text.length-1));
  447. // console.log(text.indexOf('p'));
  448. // if not there then -1
  449. // console.log(text.indexOf('e'));
  450. // console.log(text);
  451. // console.log(text.trim());
  452. // console.log(text.startsWith(' Peter'));
  453. // console.log(text.trim().toLocaleLowerCase().startsWith('peter'));
  454. // console.log(text.includes('eter'));
  455. // searches and gives back boolean
  456. // console.log(text.slice(0,2));
  457. // letter from 0 to 2
  458. // console.log(text.slice(-1));
  459. // -----------------------------------------------------
  460. // Template Literals - ES6+
  461. // Backtick characters `` - above tab (left from one)
  462. // Interpolation ${} - insert expression (value)
  463. // const name = 'john';
  464. // const age = 25;
  465. // const sentence = "Hey it's " + name + ' and he is ' + age +
  466. // ' years old';
  467. // const value = `Hey it's ${name} and he is ${age} years old.
  468. // And here is some simple math ${4+4}`;
  469. // console.log(value);
  470. // console.log(sentence);
  471. // -----------------------------------------------
  472. // Array Properties and Methods
  473. // let names = ['john','bobo','barry','olga','ben'];
  474.  
  475. // length
  476. // console.log(names.length);
  477. // console.log(names[names.length - 1]);
  478.  
  479. // concat
  480. // const lastNames = ['pepper', 'onion', 'banana'];
  481. // const allNames = names.concat(lastNames);
  482. // console.log(allNames);
  483.  
  484. // reverse
  485. // console.log(allNames.reverse());
  486.  
  487. //unshift // added at the beginning of the array
  488. // allNames.unshift('susy');
  489. // allNames.unshift('anna');
  490. // console.log(allNames);
  491.  
  492. //shift
  493. // allNames.shift();
  494. // allNames.shift();
  495. // allNames.shift();
  496. // allNames.shift();
  497. // console.log(allNames);
  498.  
  499. // push
  500. // allNames.push('susy');
  501. // console.log(allNames);
  502.  
  503. // pop
  504. // allNames.pop();
  505. // allNames.pop();
  506. // allNames.pop();
  507. // allNames.pop();
  508. // console.log(allNames);
  509.  
  510. // splice - mutates original array
  511. // const specificNames = allNames.splice(2,1);
  512. // console.log(specificNames);
  513. // console.log(allNames); // herel also removes one
  514.  
  515. // ----------------------------------------------------
  516. // ----------------------------------------------------
  517. // ----------------------------------------------------
  518. // Arrays and for-loop
  519. // const names = ['anna', 'susy', 'bob','john'];
  520. // const lastName = 'shakeandbake';
  521. // let newArray = [];
  522. // console.log( newArray);
  523. // //for loop
  524. // for(let i=0; i<names.length; i++){
  525. // console.log(i);
  526. // console.log(names[i]);
  527. // // newArray.push(names[i]);
  528. // const fullName = `${names[i]} ${lastName}`;
  529. // newArray.push(fullName);
  530.  
  531. // }
  532. // console.log(names);
  533. // console.log(newArray);
  534. // --------------------------------------------------------
  535. // *********** ---------- OBJECT --------- ****************
  536. // --------------------------------------------------------
  537. // Functions, return, if , arrays, for loop
  538. // const gas = [20,40,100];
  539. // const food = [10,40,50];
  540. // function calculateTotal(arr){
  541. // let total = 0;
  542. // for(let i=0; i<arr.length; i++){
  543. // console.log(arr[i]);
  544. // total += arr[i];
  545. // }
  546. // if(total > 100){
  547. // console.log(`whoa! You are spending way too much`);
  548. // return total;
  549. // }
  550. // console.log(`You are good, total is less than 100`);
  551. // console.log(total);
  552. // return total;
  553. // }
  554. // const gasTotal = calculateTotal(gas);
  555. // const foodTotal = calculateTotal(food);
  556. // const randomTotal = calculateTotal([200, 40000, 500, 1]);
  557.  
  558. // console.log({
  559. // gas:gasTotal,
  560. // food: foodTotal,
  561. // random: randomTotal
  562. // });
  563. // -----------------------------------------------------
  564. // -----------------------------------------------------
  565. // Reference vs Value
  566. // Primitive Data Types
  567. // String , Number, Symbol, Boolean, Undefined, Null
  568. // Arrays, Functions, Objects = Object
  569. // typeof
  570. /* When assigning primitive data type value to a variable any
  571. changes are made directly to that value, without affecting
  572. originial value */
  573.  
  574. /* When assigning non-primtive data type {such as object} value to a variable
  575. is done by reference, so any changes will affect all the
  576. references */
  577. // let number = 1;
  578. // let number2 = number;
  579. // number2 = 7;
  580. // console.log(`the first value is ${number}`);
  581. // console.log(`the second value is ${number2}`);
  582.  
  583. // let person = {name:'bob'};
  584. // let person2 = person;
  585. // let person2 = {...person}; // spread operator
  586. // person2.name = 'susy';
  587. // console.log(`the name of the first person is ${person.name}`);
  588. // console.log(`the name of the second person is ${person2.name}`);
  589.  
  590. // -------------------------------------------------------------------
  591. // Null and Undefined
  592. // both represent "no value"
  593.  
  594. // undefined - "javascript can not find value for this"
  595.  
  596. // variable without value
  597. // missing function arguments
  598. // missing object properties
  599.  
  600. // null - "developer sets value"
  601.  
  602. // let number = 20 + null; // 20 + 0
  603. // console.log(number);
  604. // let number2 = 20 + undefined;
  605. // console.log(number2);
  606.  
  607. // --------------------------------------------------------------------
  608. // Truthy and Falsy
  609. // "", '', ``, 0, -0, Nan, null, undefined
  610.  
  611. // const bool1 = true;
  612. // const bool2 = 2 > 1;
  613. // -------------------------------------------
  614. // if(bool1){
  615. // console.log(`Hey it works!`);
  616. // }
  617. // if(bool2){
  618. // console.log(`Hey it also works`);
  619. // }
  620. // -------------------------------------------
  621. // const text = '';
  622. // if(text){
  623. // console.log('hey the value is truthy');
  624. // } else {
  625. // console.log('hey the value is falsy');
  626. // }
  627. // ---------------------------------------------
  628. // unary operator - typeof
  629. // let text = 'some text';
  630. // console.log(typeof text);
  631.  
  632. // binary operator - assignment
  633. // let number = 3;
  634. // let number2 = 2+5;
  635.  
  636. // ternary operator -
  637. // condition ? (runs if true) : (runs if false)
  638. // const value = 2>1;
  639. // if(value){
  640. // console.log('value is true');
  641. // } else{
  642. // console.log('value is false');
  643. // }
  644. // ----------------------
  645. // value ? console.log('value is true'): console.log('value is false');
  646. // -------------------------------------------
  647. // ---------------------------------------------------------
  648. // Global Scope vs Local Scope
  649. // any variable outside code block {} is said to be in Global Scope
  650. // can be access anywhere in the program
  651. // Gotchas: name collisions, modify by mistake
  652.  
  653. // let name = 'bobo';
  654. // name = 'peter';
  655. // // const name1 = 'john';
  656. // console.log(`my name is ${name} and I'm a student`);
  657.  
  658. // function calculate(){
  659. // // some other code...
  660. // console.log(name);
  661. // name = 'orange';
  662. // function inner(){
  663. // name = 'inner name value';
  664. // console.log(`this is from inner function ${name}`);
  665. // }
  666. // inner();
  667. // }
  668. // calculate();
  669. // console.log(`my name is ${name} and I'm a student`);
  670.  
  671. // if(true){
  672. // // some other code...
  673. // console.log(name);
  674. // name = 'Inside if';
  675. // }
  676.  
  677. // console.log(`my name is ${name} and I'm a student`);
  678.  
  679. // -------------------------------------------------------
  680. // Local Scope
  681. // can not be access from outside code blocks
  682. // if - NOT VAR
  683. // let name = 'bobo';
  684. // function calculate(){
  685. // const name = 'john';
  686. // const age = 25;
  687. // // code goes here
  688. // becomesGlobal = 'global variable';
  689. // }
  690. // calculate();
  691. // console.log(name);
  692. // // console.log(age);
  693. // console.log(becomesGlobal);
  694.  
  695. // if(true){
  696. // const name = 'john';
  697. // }
  698.  
  699. // {
  700. // const name = 'john';
  701. // const special = 'special'
  702. // }
  703. // console.log(special);
  704.  
  705. // console.log(`my name is ${name} and I'm a student`);
  706. // -------------------------------------------------------
  707. // Variable lookup
  708. // {} - code block
  709.  
  710. // const globalNumber = 5;
  711. // function add(num1, num2){
  712. // // const globalNumber = 20;
  713. // const result = num1 + num2 + globalNumber;
  714. // function multiply(){
  715. // // const globalNumber = 100;
  716. // const multiplyResult = result * globalNumber;
  717. // console.log(multiplyResult);
  718. // }
  719. // console.log(multiplyResult);
  720. // // multiplyResult is a local variable to the multiply
  721. // // doesn't work the opossite way
  722. // // JS always goona hop outside to look for the variable
  723. // // but can't do lookup from the outside in the local scope of the function
  724. // // console - multiplyResult is not defined
  725. // multiply();
  726. // // console.log(globalNumber);
  727. // return result;
  728. // }
  729. // console.log(add(3,4));
  730. // --------------------------------------------------------------------------------
  731. // --------------------------------------------------------------------------------
  732.  
  733. // Callback Functions, Higher Order Functions,
  734. // Functions as First Class Objects/Citizens
  735.  
  736. // Functions are first class objects - stored in a variable (expression),
  737. // passed as an argument to another function, return from the function (closure)
  738.  
  739. // Higher Order Function - accepts another function as an argument or
  740. // returns another function as a result
  741.  
  742. // Callback Function - passed to a another function as an argument
  743. // and executed inside that function
  744. // -------------------------------------------------------------------------
  745. // function greetMorning(name){
  746. // const myName = 'john';
  747. // console.log(`Good morning ${name}, my name is ${myName}`);
  748. // }
  749.  
  750. // function greetAfternoon(name){
  751. // const myName = 'john';
  752. // console.log(`Good afternoon ${name}, my name is ${myName}`);
  753. // }
  754.  
  755. // greetMorning('bobo');
  756. // greetAfternoon('peter');
  757. // -------------------------------------------------------------------
  758.  
  759. // --- Call Back Function --- Below
  760. // function morning(name){
  761. // // console.log('Good morning Bob');
  762. // return `Good morning ${name.toUpperCase()}`;
  763. // }
  764.  
  765. // function afternoon(name){
  766. // return `Good morning ${name.repeat(3)}`;
  767. // }
  768.  
  769. // // --- Higher Order Function --- Below
  770. // function greet(name,cb){
  771. // const myName = 'john';
  772. // console.log(`${cb(name)}, my name is ${myName}`);
  773. // }
  774.  
  775. // greet('bobo',morning);
  776. // greet('peter ',afternoon);
  777.  
  778. // -----------------------------------------------------------------------------
  779. // Powerful Array Mehtods
  780. // forEach, map, filter, reduce
  781. // Iterate over array - no for loop required
  782. /* Accept CALLBACK function as an argument,
  783. call Callback against each item in a array.
  784. Reference Item in the Callback Parameter. */
  785.  
  786. // const numbers = [0,1,2,3,4];
  787. // // show all numbers
  788. // for(let i=0; i<numbers.length; i++){
  789. // console.log(numbers[i]);
  790. // }
  791.  
  792. // ---------------------------------------------------------------------------
  793. // To understand forEach read carefully Higher Order and Callback Function
  794. // forEach
  795. // does not return new array
  796.  
  797. // const people = [
  798. // {name: 'bob', age:20, position: 'developer'},
  799. // {name: 'peter', age:24, position: 'designer'},
  800. // {name: 'susy', age:23, position: 'engineer'},
  801. // ];
  802. // function showPerson(person){
  803. // console.log(person.name.toUpperCase());
  804. // }
  805.  
  806. // // people.forEach(showPerson);
  807. // people.forEach(function(item){
  808. // console.log(item.name.toUpperCase());
  809. // });
  810. // ----------------------------------------------------------------------------------
  811.  
  812. // map
  813. // does return a new array
  814. // does not change size of original array
  815. // uses values from original array when making new one
  816.  
  817. // const people = [
  818. // {name: 'bob', age:20, position: 'developer'},
  819. // {name: 'peter', age:24, position: 'designer'},
  820. // {name: 'susy', age:23, position: 'engineer'},
  821. // ];
  822.  
  823. // // const ages = people.map(function(){});
  824. // const ages = people.map(function(person){
  825. // // console.log(person);
  826. // return person.age + 20;
  827. // });
  828. // ----------------------------
  829. // const newPeople = people.map(function(person){
  830. // return{
  831. // firstName: person.name.toUpperCase(),
  832. // oldAge: person.age + 20,
  833. // };
  834. // });
  835. // ----------------------------
  836. // const names = people.map(function(person){
  837. // return `<h1>${person.name}</h1>`;
  838. // });
  839. // document.body.innerHTML = names.join('');
  840.  
  841. // console.log(ages);
  842. // console.log(newPeople);
  843. // console.log(names);
  844.  
  845. // -----------------------------------------------------------------------
  846. // filter
  847. // does return a new array
  848. // can manipulate the size of new array
  849. // returns based on condition
  850.  
  851. // const people = [
  852. // {name: 'bob', age:20, position: 'developer'},
  853. // {name: 'peter', age:24, position: 'designer'},
  854. // {name: 'susy', age:23, position: 'engineer'},
  855. // ];
  856.  
  857. // const youngPeople = people.filter(function(person){
  858. // return person.age <= 25;
  859. // });
  860.  
  861. // const developers = people.filter(function(person){
  862. // // return person.position === 'developer';
  863. // return person.position === 'senior developer';
  864. // });
  865.  
  866. // // console.log(youngPeople);
  867. // console.log(developers);
  868.  
  869. // ---------------------------------------------------------
  870. // find
  871. // returns single instance - (in this case object)
  872. // returns first match, if no match then undefined
  873. // great for getting unique value
  874.  
  875. // const people = [
  876. // {name: 'bob', age:20, position: 'developer', id:1},
  877. // {name: 'peter', age:24, position: 'designer', id:2},
  878. // {name: 'susy', age:23, position: 'engineer', id:3},
  879. // ];
  880.  
  881. // const names = ['bob','peter','susy'];
  882.  
  883. // const person = people.find(function(person){
  884. // return person.id === 3;
  885. // });
  886.  
  887. // console.log(
  888. // names.find(function(name){
  889. // return name === 'bob';
  890. // })
  891. // );
  892.  
  893. // // console.log(person);
  894. // console.log(person.name);
  895.  
  896. // const person2 = people.filter(function(person){
  897. // return person.id === 3;
  898. // });
  899. // // console.log(person2);
  900. // console.log(person2[0].name);
  901.  
  902. // ----------------------------------------------
  903. // reduce
  904. // iterates, callback function
  905. // reduces to a single value - number, array, object
  906. // 1 parameter ('acc') - total of all calculations
  907. // 2 parameter ('curr') - current iteration/value
  908.  
  909. // const people = [
  910. // {name: 'bob', age:20, position: 'developer', id:1, salary:200},
  911. // {name: 'peter', age:24, position: 'designer', id:2, salary:300},
  912. // {name: 'susy', age:23, position: 'engineer', id:3, salary:400},
  913. // ];
  914.  
  915. // const total = people.reduce(function(acc, currItem){
  916. // console.log(`total ${acc}`);
  917. // console.log(`current money: ${currItem.salary}`);
  918. // acc += currItem.salary;
  919. // return acc;
  920. // },0);
  921.  
  922. // console.log(total);
  923.  
  924. // --------------------------------------------------------
  925. // Math
  926. // Standard built-in objects - always available
  927. // const number = 4.56789;
  928. // const result = Math.floor(8.9999);
  929.  
  930. // const number = 4.12344;
  931. // const result = Math.ceil(number);
  932.  
  933. // const number = 64;
  934. // const result = Math.sqrt(number);
  935.  
  936. // const result = Math.PI;
  937. // const result = Math.min(4,5,6,7,9);
  938. // const result = Math.max(4,5,6,7,9,100,200,1000);
  939.  
  940. // const result = Math.floor(Math.random() * 10);
  941. // const result = Math.ceil(Math.random() * 10);
  942. // console.log(result);
  943.  
  944. // ---------------------------------------------------------
  945. // Date
  946. // const months = [
  947. // 'January','February','March','April','May','June',
  948. // 'July','August','September','October','November','December'
  949. // ];
  950.  
  951. // const days = [
  952. // 'Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'
  953. // ];
  954.  
  955. // // const date = new Date();
  956. // const date = new Date('1/12/2004');
  957. // const month = date.getMonth();
  958. // console.log(months[month]);
  959.  
  960. // const day = date.getDay();
  961. // console.log(days[day]);
  962.  
  963. // console.log(date.getDate());
  964. // console.log(date.getFullYear());
  965.  
  966. // const sentence = `${days[day]}, ${date.getDate()} ${months[month]} ${date.getFullYear()}`;
  967. // // console.log(sentence);
  968.  
  969. // document.body.innerHTML = sentence;
  970.  
  971. // -------------------------------- -------------
  972. // ----------------- DOM -----------------------------
  973. // -----------------------------------------------
  974. // Select elements
  975. // Traverse DOM
  976. // Insert/Remove Elements
  977. // Apply Styling
  978. // Add/Remove css Classes
  979. // -----------------------------------------
  980. // similar to CSS
  981. // Select the element or group of elements that we want to affect
  982. // Decide the effect we want to apply to the selection
  983.  
  984. // -------many different ways ---
  985. // document.body.style.background = 'grey';
  986. // document.body.style.color = 'yellow';
  987. // document.getElementById('btn').style.color = 'red';
  988.  
  989. // assighn to a variable
  990. // const element = document.getElementById('element');
  991.  
  992. // do something
  993. // document.querySelector('element');
  994.  
  995. // window object
  996. /* Once we included our property in our index.html
  997. we have accessd to a global window object */
  998. // console.log(window);
  999.  
  1000. // ---- returns a node object or a node list, node list is an arraylike object
  1001. // const btn = document.getElementById('btn');
  1002. // const name = btn.nodeName;
  1003. // const css = btn.style;
  1004. // console.log(btn);
  1005. // console.log(name);
  1006. // console.log(css);
  1007. // ----------------------------------------------------------------
  1008. // window object = browser api (way for browser that gives option to works with browser)
  1009. // when talkig window we are talking about the tab we are currently operating in...
  1010.  
  1011. // within the window object we have the document,
  1012. // whay we don't write window.object?
  1013.  
  1014. // document
  1015. // console.dir
  1016.  
  1017. // console.dir(document);
  1018.  
  1019. // --------------------------------------------------------------
  1020. // Select the element or group of elements that we want
  1021. // Decide the effect we want to apply to the selection
  1022.  
  1023. // getElementById('element')
  1024.  
  1025. // const h1 = document.getElementById('title');
  1026. // h1.style.color = 'red';
  1027.  
  1028. // const btn = document.getElementById('btn');
  1029. // btn.style.backgroundColor = 'blue';
  1030. // btn.style.color = 'white';
  1031.  
  1032. // -------------------------------------------------------
  1033. // getElementByTagName('tagname');
  1034. // node-list = array-like object
  1035. // index, length property but not array methods
  1036.  
  1037. // const headings = document.getElementsByTagName('h2');
  1038. // headings[0].style.color = 'red';
  1039. // console.log(headings);
  1040. // console.log(headings.length);
  1041.  
  1042. // const items = document.getElementsByTagName('li');
  1043.  
  1044. // items.forEach(function(item) {
  1045. // console.log(item);
  1046. // });
  1047.  
  1048. // items[2].style.color = 'red';
  1049.  
  1050. // const betterItems = [...items];
  1051. // betterItems.forEach(function(item){
  1052. // console.log(item);
  1053. // });
  1054.  
  1055. // console.log(items);
  1056. // console.log(betterItems);
  1057. // -------------------------------------------------
  1058.  
  1059. // getElementsByClassName('classname');
  1060.  
  1061. // node-list = array-like object
  1062. // index, length property but not array methods
  1063.  
  1064. // const listItems = document.getElementsByClassName('special');
  1065. // listItems[1].style.color = 'blue';
  1066. // ---------------------------------------------------------
  1067.  
  1068. // querySelector('any css'); - selects single
  1069. // querySelectorAll('any css'); - selects all
  1070.  
  1071. // const result = document.querySelector('#result');
  1072. // result.style.backgroundColor = 'red';
  1073.  
  1074. // const item = document.querySelector('.special');
  1075. // console.log(item);
  1076.  
  1077. // const lastItem = document.querySelector('li:last-child');
  1078. // console.log(lastItem);
  1079.  
  1080. // const list = document.querySelectorAll('.special');
  1081. // console.log(list);
  1082.  
  1083. // list.forEach(function(item){
  1084. // console.log(item);
  1085. // item.style.color = 'white';
  1086. // });
  1087. // ----------------------------------------------------------------
  1088.  
  1089. // select the element or group of elements that we want
  1090. // Decide the effect we want to apply to the selection
  1091.  
  1092. // childNodes - returns all childNodes including whitespace which
  1093. // is treated as a text node
  1094.  
  1095. // children
  1096. // firstChild
  1097. // lastChild
  1098.  
  1099. // const result = document.querySelector('#result');
  1100. // const allChildren = result.childNodes;
  1101. // // console.log(allChildren);
  1102.  
  1103. // const children = result.children;
  1104. // console.log(children);
  1105.  
  1106. // console.log(result.firstChild);
  1107. // console.log(result.lastChild);
  1108. // ----------------------------------------------
  1109.  
  1110. // const heading = document.querySelector('h2');
  1111. // console.log(heading.parentElement.parentElement.parentElement.parentElement);
  1112. // const parent = heading.parentElement;
  1113. // parent.style.color = 'red';
  1114.  
  1115. // -----------------------------------------------
  1116. // previousSibling
  1117. // nextSibling
  1118. // return whitespace
  1119.  
  1120. // const first = document.querySelector('.first');
  1121. // const second = first.nextSibling.nextSibling;
  1122. // second.style.color = 'red';
  1123. // console.log(second);
  1124.  
  1125. // const last = document.querySelector('#last');
  1126. // const third = last.previousSibling.previousSibling;
  1127. // console.log(third);
  1128. // console.log(last.nextSibling.nextSibling);
  1129.  
  1130. // -----------------------------------------------
  1131. // previousElementSibling
  1132. // nextElementSibling
  1133.  
  1134. // const first = document.querySelector('.first');
  1135. // first.nextElementSibling.style.color = 'red';
  1136. // const last = document.querySelector('#last');
  1137.  
  1138. // -----------------------------------------------------
  1139. // nodeValue
  1140. // textContent
  1141.  
  1142. // const item = document.getElementById('special');
  1143. // const value = item.firstChild.nodeValue;
  1144. // console.log(item.childNodes[0].nodeValue);
  1145. // console.log(item.firstChild.nodeValue);
  1146.  
  1147. // const easyValue = item.textContent;
  1148. // console.log(easyValue);
  1149. // -------------------------------------------------------
  1150.  
  1151. // getAttribute();
  1152. // setAttribute();
  1153.  
  1154. // const first = document.querySelector('.first');
  1155. // const classValue = first.getAttribute('class');
  1156. // console.log(classValue);
  1157.  
  1158. // const idValue = first.getAttribute('id');
  1159. // console.log(idValue);
  1160.  
  1161. // const link = document.getElementById('link');
  1162. // const showLink = link.getAttribute('href');
  1163. // console.log(showLink);
  1164.  
  1165. // const last = link.nextElementSibling;
  1166. // last.setAttribute('class','first');
  1167. // last.textContent = 'i also have a class of first';
  1168. // console.log(last);
  1169.  
  1170. // const links = document.querySelectorAll('.first');
  1171. // console.log(links);
  1172.  
  1173. // -----------------------------------------------------
  1174. // className
  1175. // classList
  1176.  
  1177. // const first = document.getElementById('first');
  1178. // const second = document.getElementById('second');
  1179. // const third = document.getElementById('third');
  1180.  
  1181. // const classValue = first.className;
  1182. // console.log(classValue);
  1183.  
  1184. // second.className = 'colors';
  1185. // second.className = 'text';
  1186. // here first class is removed when second class is initialized
  1187. // so we write as below to apply both classes,
  1188. // second.className = 'colors text';
  1189.  
  1190. // third.classList.add('colors','text');
  1191. // third.classList.add('text');
  1192. // third.classList.remove('text');
  1193.  
  1194.  
  1195. // const result = third.classList.contains('colors');
  1196. // if(result){
  1197. // console.log('hello world');
  1198. // } else {
  1199. // console.log('does not have the class');
  1200. // }
  1201.  
  1202. // const classValue = third.classList;
  1203. // console.log(classValue);
  1204. // -----------------------------------------------------
  1205. // createElement('element')
  1206. // createTextNode('text content')
  1207. // element.appendChild(childElement)
  1208.  
  1209. // insertBefore('element', 'location');
  1210.  
  1211. // replaceChild('new', 'old');
  1212.  
  1213. // const result = document.querySelector('#result');
  1214. // const first = document.querySelector('.red');
  1215.  
  1216. // create empty element
  1217. // const bodyDiv = document.createElement('div');
  1218. // create text node
  1219. // const text = document.createTextNode('a simple body div');
  1220. // bodyDiv.appendChild(text);
  1221. // document.body.appendChild(bodyDiv);
  1222.  
  1223. // document.body.insertBefore(bodyDiv, result);
  1224.  
  1225. // result element
  1226. // const heading = document.createElement('h2');
  1227. // const headingText = document.createTextNode('dynamic heading');
  1228. // heading.appendChild(headingText);
  1229. // heading.classList.add('blue');
  1230. // result.appendChild(heading);
  1231.  
  1232. // Before
  1233. // result.insertBefore(heading,first);
  1234.  
  1235. // ----- replaceChild --------
  1236. // const smallHeading = document.createElement('h6');
  1237. // const smallText = document.createTextNode(`i'm a small heading text`);
  1238. // smallHeading.classList.add('red');
  1239. // smallHeading.appendChild(smallText);
  1240. // document.body.replaceChild(smallHeading,bodyDiv);
  1241.  
  1242. // console.log(result.children);
  1243.  
  1244. // ----------------------------------------------------
  1245. // prepend
  1246. // innerText
  1247.  
  1248. // const heading = document.createElement('h2');
  1249. // heading.innerText = `i am a dyanamic heading`;
  1250. // document.body.prepend(heading);
  1251.  
  1252. // ------------------------------------------------
  1253. // remove
  1254. // removeChild
  1255. // const result = document.querySelector('#result');
  1256. // result.remove();
  1257.  
  1258. // const heading = result.querySelector('h1');
  1259. // result.removeChild(heading);
  1260. // console.log(heading);
  1261.  
  1262. // -------------------------------------------------
  1263. // innerHTML
  1264. // textContent
  1265.  
  1266. // const list = document.getElementById('first');
  1267. // const div = document.getElementById('second');
  1268. // const item = document.querySelector('.item');
  1269.  
  1270. // console.log(div.textContent);
  1271. // console.log(list.innerHTML);
  1272. // console.log(list.textContent);
  1273.  
  1274. // const randomVar = 'random value';
  1275.  
  1276. // const ul = document.createElement('ul');
  1277. // ul.innerHTML = `<li class="item">${randomVar}</li>
  1278. // <li>list item</li> <li>list item</li>`;
  1279. // document.body.appendChild(ul);
  1280.  
  1281. // div.textContent = 'hello world';
  1282. // div.innerHTML = 'hello people';
  1283.  
  1284.  
  1285. // div.textContent = `<li class="item">${randomVar}</li>
  1286. // <li>list item</li> <li>list item</li>`;
  1287. // div.innerHTML = `<li class="item">${randomVar}</li>
  1288. // <li>list item</li> <li>list item</li>`;
  1289.  
  1290. // --------------------------------------------------------
  1291. // CSS
  1292. // const random = document.querySelector('.random');
  1293.  
  1294. // random.style.backgroundColor = 'blue';
  1295. // random.style.color = 'white';
  1296. // random.style.fontSize = '3rem';
  1297. // random.style.textTransform = 'capitalize';
  1298.  
  1299. // random.classList.add('title');
  1300.  
  1301. // -----------------------------------------------------
  1302. // select element
  1303. // addEventListener()
  1304. // what event, what to do
  1305.  
  1306. // const btn = document.querySelector('.btn');
  1307. // const heading = document.querySelector('h2');
  1308.  
  1309. // btn.addEventListener('click', function(){
  1310. // // console.log('hey you clicked me');
  1311. // heading.classList.add('red');
  1312. // });
  1313. // --------------------------
  1314. // function changeColors(){
  1315. // // console.log('hello');
  1316. // let hasClass = heading.classList.contains('red');
  1317. // if(hasClass){
  1318. // heading.classList.remove('red');
  1319. // } else{
  1320. // heading.classList.add('red');
  1321. // }
  1322. // }
  1323. // // invoked here
  1324. // // btn.addEventListener('click',changeColors());
  1325.  
  1326. // // here passing it as a reference
  1327. // btn.addEventListener('click',changeColors);
  1328. // ------------------------------------------------------
  1329. // click - fires after full action occurs
  1330. // mousedown - button is pressed
  1331. // mousedown - button is released
  1332. // mouseenter - moved onto an element
  1333. // mouseleave - moved out of an element
  1334.  
  1335. // const heading = document.querySelector('h1');
  1336. // const btn = document.querySelector('.btn');
  1337.  
  1338. // btn.addEventListener('click',function(){
  1339. // console.log('you clicked me');
  1340. // });
  1341.  
  1342. // btn.addEventListener('mousedown',function(){
  1343. // console.log('down');
  1344. // });
  1345.  
  1346. // btn.addEventListener('mouseup',function(){
  1347. // console.log('up');
  1348. // });
  1349.  
  1350. // heading.addEventListener('mouseenter', function(){
  1351. // heading.classList.add('blue');
  1352. // });
  1353.  
  1354. // heading.addEventListener('mouseleave', function(){
  1355. // heading.classList.remove('blue');
  1356. // });
  1357.  
  1358. // -----------------------------------------------
  1359. // keypress - when key is pressed
  1360. // keydown - when key is down
  1361. // keyup - when key is released
  1362.  
  1363. // const nameInput = document.getElementById('name');
  1364.  
  1365. // nameInput.addEventListener('keypress', function(){
  1366. // console.log('you pressed a key');
  1367. // });
  1368.  
  1369. // nameInput.addEventListener('keydown', function(){
  1370. // console.log('you pressed a key');
  1371. // });
  1372.  
  1373. // nameInput.addEventListener('keyup', function(){
  1374. // // console.log('you pressed a key');
  1375. // // console.dir(nameInput);
  1376. // console.log(nameInput.value);
  1377. // });
  1378.  
  1379. // --------------------------------------------------------
  1380. // event object, argument e, evt
  1381. // info about triggered event
  1382. // event.type
  1383. // event.currentTarget
  1384. // this keyword
  1385. // preventDefault() - prevents default behavior
  1386.  
  1387. // const heading = document.querySelector('h1');
  1388. // const btn = document.querySelector('.btn');
  1389. // const link = document.getElementById('link');
  1390.  
  1391. // heading.addEventListener('click', event => {
  1392. // console.log(event.currentTarget);
  1393. // console.log(this);
  1394. // });
  1395.  
  1396. // heading.addEventListener('click', function(event){
  1397. // // console.log(event.currentTarget);
  1398. // event.currentTarget.classList.add('blue');
  1399. // });
  1400.  
  1401. // btn.addEventListener('click', function(event){
  1402. // console.log(event.currentTarget);
  1403. // event.currentTarget.classList.add('blue');
  1404. // console.log(event.type);
  1405. // });
  1406.  
  1407. // // prevent default
  1408. // function someFunc(e){
  1409. // e.preventDefault();
  1410. // }
  1411.  
  1412. // link.addEventListener('click',someFunc);
  1413.  
  1414. // ---------------------------------------------------------
  1415. // currentTarget - always refers to the element to which the event
  1416. // handler has been attached to...
  1417. // target - identifies the element on which the event occured
  1418.  
  1419. // const btns = document.querySelectorAll('.btn');
  1420.  
  1421. // btns.forEach(function(btn){
  1422. // btn.addEventListener('click',function(e){
  1423. // // console.log(e.currentTarget);
  1424. // // e.currentTarget.style.color = 'black';
  1425. // // -----------------------------------------
  1426. // console.log('target',e.target);
  1427. // console.log('currentTarget',e.currentTarget);
  1428. // e.target.style.color = 'black';
  1429.  
  1430. // });
  1431. // });
  1432.  
  1433. // ----------------------------------------------------------
  1434. // allows select dynamic elements
  1435. // event propogation - order the events are fired
  1436. // event bubbling - clicked element first then bubbles up -- default
  1437. // event capturing - fires at the root and fires until reaches target
  1438.  
  1439. // const container = document.querySelector('.container');
  1440. // const list = document.querySelector('.list-items');
  1441.  
  1442. // function showBubbling(e){
  1443. // console.log('current target', e.currentTarget);
  1444. // console.log('target',e.target);
  1445. // if(e.target.classList.contains('link')){
  1446. // console.log('you clicked on the link');
  1447. // }
  1448. // }
  1449.  
  1450. // function stopPropagation(e){
  1451. // console.log('you clicked on list');
  1452. // e.stopPropagation();
  1453. // }
  1454.  
  1455. // list.addEventListener('click',stopPropagation);
  1456. // container.addEventListener('click',showBubbling);
  1457. // document.addEventListener('click',showBubbling);
  1458. // window.addEventListener('click',showBubbling);
  1459. // list.addEventListener('click',showBubbling);
  1460. // -------------------------------------------------
  1461. // event capturing
  1462. // container.addEventListener('click',showBubbling,{capture:true});
  1463. // document.addEventListener('click',showBubbling,{capture:true});
  1464. // window.addEventListener('click',showBubbling,{capture:true});
  1465. // list.addEventListener('click',showBubbling,{capture:true});
  1466.  
  1467. // -------------------------------------------------------------
  1468. // allows select dynamic elements
  1469. // event propogation - order the events are fired
  1470. // event bubbling - clicked element first then bubbles up -- default
  1471.  
  1472. // const container = document.querySelector('.container');
  1473. // const btn = document.querySelector('.btn');
  1474. // const heading = document.querySelector('.heading');
  1475.  
  1476. // console.log(heading);
  1477.  
  1478. // function sayHello(){
  1479. // console.log('hello there');
  1480. // }
  1481.  
  1482. // btn.addEventListener('click', function(){
  1483. // const element = document.createElement('h1');
  1484. // element.classList.add('heading');
  1485. // element.textContent = `i'm inside the container`;
  1486. // container.appendChild(element);
  1487. // });
  1488.  
  1489. // container.addEventListener('click',function(e){
  1490. // if(event.target.classList.contains('heading')){
  1491. // console.log('hello there');
  1492. // }
  1493. // });
  1494.  
  1495. // heading.addEventListener('click',sayHello);
  1496.  
  1497. // -----------------------------------------------------------
  1498. // submit event listener
  1499. // prevent default
  1500. // how to get a value
  1501.  
  1502. // const form = document.getElementById('form');
  1503. // const name = document.getElementById('name');
  1504. // const password = document.getElementById('password');
  1505.  
  1506. // form.addEventListener('submit', function(e){
  1507. // // e.preventDefault();
  1508. // console.log('form submitted');
  1509. // console.log(name.value);
  1510. // console.log(password.value);
  1511. // });
  1512.  
  1513. // -----------------------------------------------------------------
  1514. // Web storage API - provided by browser
  1515. // session storage, local storage
  1516. // setItem, getItem, removeItem, clear
  1517.  
  1518. // localStorage.setItem('name', 'john');
  1519. // sessionStorage.setItem('name', 'john');
  1520.  
  1521. // localStorage.setItem('name','john');
  1522. // localStorage.setItem('friend','peter');
  1523. // localStorage.setItem('job','developer');
  1524. // localStorage.setItem('address','street 123');
  1525.  
  1526. // const name = localStorage.getItem('name');
  1527. // console.log(name);
  1528.  
  1529. // localStorage.removeItem('name');
  1530.  
  1531. // const anotherName = localStorage.getItem('name');
  1532. // console.log(anotherName);
  1533.  
  1534. // localStorage.clear();
  1535.  
  1536. // --------------------------------------------------------------
  1537. // JSON.stringify(), JSON.parse()
  1538.  
  1539. // const friends = ['john', 'peter', 'bob'];
  1540. // // localStorage.setItem('friends', friends);
  1541. // localStorage.setItem('friends', JSON.stringify(friends));
  1542.  
  1543. // // const values = localStorage.getItem('friends');
  1544. // const values = JSON.parse(localStorage.getItem('friends'));
  1545. // console.log(values[2]);
  1546.  
  1547.  
  1548. // let fruits;
  1549.  
  1550. // if(localStorage.getItem('fruits')){
  1551. // fruits = JSON.parse(localStorage.getItem('fruits'));
  1552. // } else {
  1553. // fruits = [];
  1554. // }
  1555. // console.log(fruits);
  1556.  
  1557. // // fruits.push('apple');
  1558. // fruits.push('orange');
  1559. // localStorage.setItem('fruits', JSON.stringify(fruits));
  1560.  
Add Comment
Please, Sign In to add comment