Advertisement
wingman007

ES6tut_es6tut.js

Dec 22nd, 2016
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. // function and block scope let and var
  3. // https://www.youtube.com/watch?v=Jakoi0G8lBg
  4. // https://mind42.com/mindmap/ba87925c-9a13-447c-86ee-e3a71ee4d122
  5. // http://www.newthinktank.com/2016/12/ecmascript-6-tutorial/
  6. // the tutor done by me is in c:\project\ecmascript6tutor Win7 ns2 comp
  7. // I useed Atom as IDE
  8.  
  9. if (true) {
  10.   var x = 10;
  11.   document.write("x = " + x + "<br />"); // 10
  12. }
  13. document.write("x = " + x + "<br />"); // 10
  14.  
  15. // block scope
  16. if (true) {
  17.   let x = 5;
  18.   document.write("x = " + x + "<br />"); // 5
  19. }
  20. document.write("x = " + x + "<br />"); // 10
  21.  
  22.  
  23. const PI = 3.14;
  24. // PI = 2.79; // Error es6tut.js:18 Uncaught TypeError: Assignment to constant variable.(…)
  25.  
  26. // The constants are global but in different blocks you can assign  the const with the same name
  27. if (true) {
  28.     // PI = 2.79; // Error es6tut.js:18 Uncaught TypeError: Assignment to constant variable.(…)
  29.     // but
  30.   const PI = 2.79;
  31. }
  32.  
  33. // loosly typed or dynamic still
  34. document.write(typeof true + "<br />"); //boolean in C# bool
  35. document.write(typeof 3.14 + "<br />"); //number in C#  double, float, decimal
  36. document.write(typeof 2 + "<br />"); //number in C# byte, short, int, long
  37. document.write(typeof "I am a string" + "<br />"); // string in C# string
  38. document.write(typeof 'I' + "<br />"); //string in C# char
  39. document.write(typeof new Array() + "<br />"); //object in C# object
  40. document.write(typeof new Object() + "<br />"); //object in C# object
  41. document.write(typeof Symbol() + "<br />"); //symbol in C# object
  42. document.write(typeof [1,2,6] + "<br />"); //object in C# object
  43. document.write(typeof {name : 'Stoyan', family: "Cheresharov"} + "<br />"); //object in C# object
  44. // document.write(typeof {'Stoyan',"Cheresharov"} + "<br />"); //es6tut.js:38 Uncaught SyntaxError: Unexpected token ,
  45. // document.write(typeof {'Stoyan'} + "<br />"); //es6tut.js:38 Uncaught SyntaxError: Unexpected token }
  46. document.write(typeof undefined + "<br />"); //undefined in C# object
  47.  
  48. /*
  49. The result:
  50. boolean
  51. number
  52. number
  53. string
  54. string
  55. object
  56. object
  57. symbol
  58. object
  59. object
  60. undefined
  61. */
  62.  
  63.  
  64. // strings
  65. // template literals
  66. let firstName = "Stoyan";
  67. let lastName = "Cheresharov";
  68. document.write(`Hello! My name is ${firstName} ${lastName}.<br />`); // Hello! My name is Stoyan Cheresharov. in C# Console.Write($"firstName falilyName")
  69.  
  70. let num1 = 10;
  71. let num2 = 5;
  72.  
  73. document.write(`${num1} + ${num2} = ${num1 + num2}<br />`); // 10 + 5 = 15
  74.  
  75.  
  76. // Tagged Template literals
  77. function doMath(strings, ...values) {
  78.   if (strings[0] == 'Add') {
  79.     document.write(`${values[0]} + ${values[1]} = ${values[0] + values[1]} <br />`);
  80.   } else if (strings[0] === 'Sub') {
  81.     document.write(`${values[0]} - ${values[1]} = ${values[0] - values[1]} <br />`);
  82.   }
  83. }
  84.  
  85. doMath `Add${10} ${5}`; // 10 + 5 = 15
  86. doMath `Sub${10} ${5}`; // 10 - 5 = 5
  87.  
  88. // for of
  89. for (let c of firstName) {
  90.   document.write(`${c} <br />`);
  91. }
  92. /*
  93. S
  94. t
  95. o
  96. y
  97. a
  98. n
  99. */
  100.  
  101. // for in - the standard JavaScript loop
  102. let myArray = [1,2,3,4,5,6,7,10];
  103. for (let element in myArray) {
  104.   document.write(`${element} <br />`);
  105. }
  106. /*
  107. 0
  108. 1
  109. 2
  110. 3
  111. 4
  112. 5
  113. 6
  114. 7
  115. */
  116.  
  117. // strings
  118. document.write("Hello".repeat(3) + "<br />"); // HelloHelloHello
  119. document.write(firstName.startsWith("St") + "<br />"); // true
  120. document.write(firstName.endsWith("St") + "<br />"); // false
  121. document.write(firstName.includes("St") + "<br />"); // true
  122.  
  123. let multiline = "This is a multiline \
  124. string. The new lines are marked \
  125. with back slash \\.";
  126.  
  127. // or
  128. let multiline2 = `This is a multiline \
  129. string. The new lines are marked \
  130. with back slash \\.`;
  131.  
  132. document.write(multiline + "<br />"); // This is a multiline string. The new lines are marked with back slash \.
  133.  
  134. document.write(multiline2 + "<br />"); // This is a multiline string. The new lines are marked with back slash \.
  135.  
  136.  
  137. // functions
  138. // default parameters
  139. function getSum(num1 = 1, num2 = 3) {
  140.   document.write(`${num1} + ${num2} = ${num1 + num2} <br />`);
  141.   // arguments dont take the default values
  142.   // arguments - array like
  143.     document.write(`${arguments[0]} + ${arguments[1]} = ${arguments[0] + arguments[1]} <br />`); // undefined + undefined = NaN
  144. }
  145.  
  146. // document.write(`${getSum()} + <br />`); // somethign undefined
  147. getSum(); // 1 + 3 = 4
  148.  
  149. function getSum2(num1 = 1, num2 = 3) {
  150.   return num1 + num2;
  151. }
  152.  
  153. document.write(`${getSum2()} <br />`); // 4
  154. document.write(`${getSum2(12)} <br />`); // 15 - because the first num1 = 12 but the second has default value
  155.  
  156.  
  157. // 13:48 Rest Parameters
  158.  
  159. function getSumMore(...values) { // you can use arguments array like or these rest
  160.   let sum = 0; // sum is visible inside the block. Block scope the sum remains 0
  161.   // var sum = 0;
  162.   for (let i = 0; i < values.length; i++) {
  163.     sum += values[i];
  164.   }
  165.   document.write(`The sum is ${sum} <br />`);
  166. }
  167.  
  168.  
  169. getSumMore(1,2,3,4,5,6,7,8); // The sum is 36
  170.  
  171. let mySecondArray = [1,2,3,4,15];
  172.  
  173. getSumMore(...mySecondArray); // The sum is 25
  174.  
  175. // Arrow functions
  176. let difference = (num1, num2) => num1 - num2; // expression
  177.  
  178. document.write(`${difference(1,2)}<br />`); // -1
  179.  
  180. // statemnt
  181. let mult = (num1, num2) => {
  182.   let product = num1 * num2;
  183.   return product;
  184. };
  185.  
  186. document.write(`The result of mul = ${mult(10,3)} <br />`); // The result of mul = 30
  187.  
  188.  
  189. // Reduce
  190. let valArr = [1,2,3,4];
  191.  
  192. let sumVal = valArr.reduce((a,b) => a + b); // let say we want to find the sume of the elements and return only 1 value
  193. document.write(`The result of reduce = ${sumVal} <br />`); // The result of reduce = 10
  194.  
  195. // Filters
  196. let odds = valArr.filter(a => a % 2); // this also woks
  197. let evens = valArr.filter(a => a % 2 == 0);
  198. document.write(`${evens} <br />`); // 2,4
  199. //!!!  we don't need to cycle trough
  200. for (let v of evens) {
  201.   document.write(`${v} <br />`);
  202. }
  203. /*
  204. 2
  205. 4
  206. */
  207.  
  208. // Map
  209.  
  210. let doubles = valArr.map(v => v * 2);
  211.   document.write(`${doubles} <br />`); // 2,4,6,8
  212.  
  213.  
  214. // Object literals
  215. function createAnimal(name, owner){ // You always have been able to do so
  216.   return {
  217.     name,
  218.     owner,
  219.     getInfo(){
  220.       return `${this.name} is owned by ${this.owner}`
  221.     },
  222.     address : {
  223.       street: "123 main streat",
  224.       city: 'Pitsburg'
  225.     }
  226.   };
  227. }
  228.  
  229. // make the difference
  230. // document.write(typeof {'Stoyan',"Cheresharov"} + "<br />"); //es6tut.js:38 Uncaught SyntaxError: Unexpected token ,
  231. // document.write(typeof {'Stoyan'} + "<br />"); //es6tut.js:38 Uncaught SyntaxError: Unexpected token }
  232.  
  233. var spot = createAnimal("Spot", "Dug");
  234.  
  235. document.write(`${spot.getInfo()}<br />`); // Spot is owned by Dug
  236.  
  237.  
  238. // as a difference The old style
  239. function createAnimalOld(name, owner){ // You always have been able to do so
  240.   return {
  241.     'name': name,
  242.     owner: owner,
  243.     getInfo: function(){
  244.       // return `${this.name} is owned by ${this.owner}`
  245.       return this.name + ' is owned by ' + this.owner;
  246.     },
  247.     address : {
  248.       street: "123 main streat",
  249.       city: 'Pitsburg'
  250.     }
  251.   };
  252. }
  253.  
  254. var barOldStyle = createAnimalOld('Bary', 'Stoyan');
  255.  
  256. document.write(`${barOldStyle.getInfo()}<br />`); // Bary is owned by Stoyan
  257.  
  258.  
  259. document.write(`${Object.getOwnPropertyNames(spot).join(' ')} <br />`); // name owner getInfo address
  260.  
  261.  
  262.  
  263.  
  264. // 22:23 Destructoring
  265. let {name, owner} = spot; // We had the similar thing in PHP
  266. document.write(`Name: ${name} <br />`); // Name: Spot
  267.  
  268. let {address} = spot;
  269. document.write(`Name: ${address.street} <br />`); // Name: 123 main streat
  270.  
  271. // Destructoring arrays
  272. let favNums = [2.5435, .3543, 4.654];
  273. let[,,chaos] = favNums;
  274. document.write(`${chaos}<br />`); // 4.654
  275.  
  276. let [,...last2] = favNums;
  277. document.write(`${last2}<br />`); // 0.3543,4.654
  278.  
  279. // switch values without using 3-th variable
  280. let val1 = 1, val2 = 2;
  281. [val1, val2] = [val2, val1];
  282. document.write(`${val2}<br />`); // 1
  283.  
  284.  
  285. // Classes
  286. class Mammal {
  287.   constructor(name){
  288.     this._name = name; // protected automatic field
  289.   }
  290.  
  291.   get name() {
  292.     return this._name;
  293.   }
  294.  
  295.   set name(name){
  296.     this._name = name;
  297.   }
  298.  
  299.   static makeMammal(name){
  300.     return new Mammal(name);
  301.   }
  302.  
  303.   // regular old methods
  304.   getInfo(){
  305.     return `${this._name} is a mammal`;
  306.   }
  307. }
  308.  
  309. let monkey = new Mammal('Fred');
  310.  
  311. monkey.name = 'Mark';
  312. document.write(`Mammal: ${monkey.getInfo()} <br />`); // Mammal: Mark is a mammal
  313.  
  314. let chipmunk = Mammal.makeMammal("Stoyan");
  315. document.write(`Mammal 2: ${chipmunk.getInfo()} <br />`); // Mammal: Stoyan is a mammal
  316.  
  317.  
  318. class Marsupial extends Mammal{
  319.   constructor(name, hasPouch){
  320.     super(name); // call the base super
  321.     this._hasPouch = hasPouch;
  322.   }
  323.  
  324.   get hasPouch() {
  325.     return this._hasPouch;
  326.   }
  327.  
  328.   set hasPouch(hasPouch){
  329.     this._hasPouch = haspouch;
  330.   }
  331.  
  332.   getInfo(){ // overriding the method
  333.     return `${this.name} is a marsupial`;
  334.   }
  335.  
  336. }
  337.  
  338. let kangaroo = new Marsupial('Paul', true);
  339.  
  340. document.write(`It is ${kangaroo.hasPouch} that ${kangaroo.name} has a pouch!<br />`); // It is true that Paul has a pouch!
  341.  
  342. document.write(`kangaroo: ${kangaroo.getInfo()} <br />`); // kangaroo: Paul is a marsupial
  343. document.write(`Mammal 2: ${chipmunk.getInfo()} <br />`); // Mammal 2: Stoyan is a mammal
  344.  
  345.  
  346. // conditional inheritance
  347. // Dynamic class
  348.  
  349. function getClass(classType){
  350.   if (classType == 1) {
  351.     return Mammal;
  352.   } else {
  353.     return Marsupial;
  354.   }
  355. }
  356.  
  357. class Koala extends getClass(2){
  358.   constructor(name){
  359.     super(name);
  360.   }
  361. }
  362.  
  363. let carl = new Koala('Carl');
  364. document.write(`${carl.getInfo()} <br />`); // Carl is a marsupial
  365.  
  366.  
  367. // Symbols
  368.  
  369. // let capital = new Symbol("State capital. This description is For debug purposes only."); // es6tut.js:363 Uncaught TypeError: Symbol is not a constructor(…)
  370. let capital = Symbol("State capital. This description is For debug purposes only.");
  371.  
  372. let pennsylvania = {};
  373. pennsylvania[capital] = "Harrisburg";
  374. document.write(`The capital of Pennsylvania is : ${pennsylvania[capital]} <br />`); // The capital of Pennsylvania is : Harrisburg
  375. document.write(`Symbol description : ${capital.toString()} </br>`);  // Symbol description : Symbol(State capital. This description is For debug purposes only.)
  376.  
  377. // share Symbols
  378. let employNum = Symbol.for("Employee number");
  379.  
  380. let bobSmith = {};
  381. bobSmith[employNum] = 10;
  382.  
  383. let sallyMarks = {};
  384. sallyMarks[employNum] = 5;
  385.  
  386. document.write(`Sally: ${sallyMarks[employNum]} Bob: ${bobSmith[employNum]} <br />`); // Sally: 5 Bob: 10
  387.  
  388. // arrays
  389. let array1 = Array.of(1,2,3); // notice no new
  390. let array2 = Array.from("word");
  391. let array3 = Array.from(array1, (value) => value * 2);
  392. for (let val of array1){
  393.   document.write(`${val} <br />`); // 123
  394. }
  395. /*
  396. 1
  397. 2
  398. 3
  399. */
  400. document.write(`${array1} <br />`); // 1,2,3 |
  401. document.write(`${array2} <br />`); //  w,o,r,d |
  402. document.write(`${array3} <br />`); //  2,4,6
  403.  
  404. // Set a set of values without duplication
  405.  
  406. var randSet = new Set();
  407. randSet.add(10);
  408. randSet.add('word');
  409.  
  410. document.write(`${randSet.has(10)} <br />`); // true
  411. document.write(`${randSet.size} <br />`); // 2
  412.  
  413. randSet.delete(10);
  414.  
  415. document.write(`${randSet.size} <br />`); // 1
  416.  
  417.  
  418. for (let val of randSet) {
  419.   document.write(`${val} <br />`);
  420. }
  421.  
  422.  
  423. // Map is a collection of key => value pairs
  424. var randMap = new Map();
  425. randMap.set("key1", "First value");
  426. randMap.set('key2', "Second value");
  427.  
  428. document.write(`${randMap.get('key1')}<br />`); // First value
  429. document.write(`${randMap.get("key2")}<br />`); // Second value
  430. document.write(`${randMap.size}<br />`); // Second value
  431. randMap.forEach(function(value, key) {
  432.   document.write(`${key} ${value}<br />`);
  433. });
  434. /*
  435. key1 First value
  436. key2 Second value
  437. */
  438.  
  439. // Promises - define code that is going to be executed later. They either susseed or family
  440. // They will have a state of fulfilled, rejected, pending, sdled???
  441.  
  442.  
  443. // Promise that is handled imediately
  444. var p1 = Promise.resolve('Resolve me');
  445.  
  446. p1.then((res) => document.write(`${res}<br />`)); // Resolve me. the second method is option in case of failiar
  447.  
  448. // promise that will execute after 2 sec
  449. var p2 = new Promise(function(resolve, reject){ // resolve will be replaced with whatever you get from the caller
  450. //  window.setTimeout(function(){
  451.     // do something
  452. //  }, 2000);
  453.   window.setTimeout(() => resolve('Resolve Me'), 4000);
  454. });
  455.  
  456. p2.then((res) => document.write(`${res}<br />`)); // when this gets executed do whatever get from resolve
  457. // clear the screen in 2 secs and writes "Resolve Me"
  458.  
  459. // promise can be fulfilled or rejected
  460. let randval = 18;
  461.  
  462. var p3 = new Promise(function(resolve, reject){ // when the promise finishes will cal resolve or reject
  463.   if (randVal == 6) {
  464.     resolve('Good Value'); // calls the callback
  465.   } else {
  466.     reject('Bad value');
  467.   }
  468. });
  469.  
  470. p3.then(
  471.   // res is an argument comming from the promise
  472.   (res) => document.write(`The promise was fullfiled and it calls resolved with whatever I put here as a function ${res}<br />`),
  473.   (rej) => document.write(`This function is called in case of rejection and rej gets its value as a formal or argument ${rej}<br />`)
  474. );
  475. // This function is called in case of rejection and rej gets its value as a formal or argument ReferenceError: randVal is not defined
  476.  
  477. // Add catch to the chain to catch the exceptions
  478. let randVal = 18; // !!! it still works we have this variable declared above
  479. var p4 = new Promise((resolve, reject) => {
  480.   if (randVal <= 17) {
  481.     // resolve("Can't vote"); // calls the callback
  482.      throw new Error("Can't vote");
  483.   } else {
  484.     resolve('Can vote');
  485.     // reject('Bad value');
  486.   }
  487. });
  488.  
  489. p4.then((val) => document.write(`${val}<br />`))
  490.   .catch((err) => document.write(`${err.message}<br />`)); // Can vote
  491.  
  492. // alert("I am here!");
  493. console.log("I am here");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement