Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // function and block scope let and var
- // https://www.youtube.com/watch?v=Jakoi0G8lBg
- // https://mind42.com/mindmap/ba87925c-9a13-447c-86ee-e3a71ee4d122
- // http://www.newthinktank.com/2016/12/ecmascript-6-tutorial/
- // the tutor done by me is in c:\project\ecmascript6tutor Win7 ns2 comp
- // I useed Atom as IDE
- if (true) {
- var x = 10;
- document.write("x = " + x + "<br />"); // 10
- }
- document.write("x = " + x + "<br />"); // 10
- // block scope
- if (true) {
- let x = 5;
- document.write("x = " + x + "<br />"); // 5
- }
- document.write("x = " + x + "<br />"); // 10
- const PI = 3.14;
- // PI = 2.79; // Error es6tut.js:18 Uncaught TypeError: Assignment to constant variable.(…)
- // The constants are global but in different blocks you can assign the const with the same name
- if (true) {
- // PI = 2.79; // Error es6tut.js:18 Uncaught TypeError: Assignment to constant variable.(…)
- // but
- const PI = 2.79;
- }
- // loosly typed or dynamic still
- document.write(typeof true + "<br />"); //boolean in C# bool
- document.write(typeof 3.14 + "<br />"); //number in C# double, float, decimal
- document.write(typeof 2 + "<br />"); //number in C# byte, short, int, long
- document.write(typeof "I am a string" + "<br />"); // string in C# string
- document.write(typeof 'I' + "<br />"); //string in C# char
- document.write(typeof new Array() + "<br />"); //object in C# object
- document.write(typeof new Object() + "<br />"); //object in C# object
- document.write(typeof Symbol() + "<br />"); //symbol in C# object
- document.write(typeof [1,2,6] + "<br />"); //object in C# object
- document.write(typeof {name : 'Stoyan', family: "Cheresharov"} + "<br />"); //object in C# object
- // document.write(typeof {'Stoyan',"Cheresharov"} + "<br />"); //es6tut.js:38 Uncaught SyntaxError: Unexpected token ,
- // document.write(typeof {'Stoyan'} + "<br />"); //es6tut.js:38 Uncaught SyntaxError: Unexpected token }
- document.write(typeof undefined + "<br />"); //undefined in C# object
- /*
- The result:
- boolean
- number
- number
- string
- string
- object
- object
- symbol
- object
- object
- undefined
- */
- // strings
- // template literals
- let firstName = "Stoyan";
- let lastName = "Cheresharov";
- document.write(`Hello! My name is ${firstName} ${lastName}.<br />`); // Hello! My name is Stoyan Cheresharov. in C# Console.Write($"firstName falilyName")
- let num1 = 10;
- let num2 = 5;
- document.write(`${num1} + ${num2} = ${num1 + num2}<br />`); // 10 + 5 = 15
- // Tagged Template literals
- function doMath(strings, ...values) {
- if (strings[0] == 'Add') {
- document.write(`${values[0]} + ${values[1]} = ${values[0] + values[1]} <br />`);
- } else if (strings[0] === 'Sub') {
- document.write(`${values[0]} - ${values[1]} = ${values[0] - values[1]} <br />`);
- }
- }
- doMath `Add${10} ${5}`; // 10 + 5 = 15
- doMath `Sub${10} ${5}`; // 10 - 5 = 5
- // for of
- for (let c of firstName) {
- document.write(`${c} <br />`);
- }
- /*
- S
- t
- o
- y
- a
- n
- */
- // for in - the standard JavaScript loop
- let myArray = [1,2,3,4,5,6,7,10];
- for (let element in myArray) {
- document.write(`${element} <br />`);
- }
- /*
- 0
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- */
- // strings
- document.write("Hello".repeat(3) + "<br />"); // HelloHelloHello
- document.write(firstName.startsWith("St") + "<br />"); // true
- document.write(firstName.endsWith("St") + "<br />"); // false
- document.write(firstName.includes("St") + "<br />"); // true
- let multiline = "This is a multiline \
- string. The new lines are marked \
- with back slash \\.";
- // or
- let multiline2 = `This is a multiline \
- string. The new lines are marked \
- with back slash \\.`;
- document.write(multiline + "<br />"); // This is a multiline string. The new lines are marked with back slash \.
- document.write(multiline2 + "<br />"); // This is a multiline string. The new lines are marked with back slash \.
- // functions
- // default parameters
- function getSum(num1 = 1, num2 = 3) {
- document.write(`${num1} + ${num2} = ${num1 + num2} <br />`);
- // arguments dont take the default values
- // arguments - array like
- document.write(`${arguments[0]} + ${arguments[1]} = ${arguments[0] + arguments[1]} <br />`); // undefined + undefined = NaN
- }
- // document.write(`${getSum()} + <br />`); // somethign undefined
- getSum(); // 1 + 3 = 4
- function getSum2(num1 = 1, num2 = 3) {
- return num1 + num2;
- }
- document.write(`${getSum2()} <br />`); // 4
- document.write(`${getSum2(12)} <br />`); // 15 - because the first num1 = 12 but the second has default value
- // 13:48 Rest Parameters
- function getSumMore(...values) { // you can use arguments array like or these rest
- let sum = 0; // sum is visible inside the block. Block scope the sum remains 0
- // var sum = 0;
- for (let i = 0; i < values.length; i++) {
- sum += values[i];
- }
- document.write(`The sum is ${sum} <br />`);
- }
- getSumMore(1,2,3,4,5,6,7,8); // The sum is 36
- let mySecondArray = [1,2,3,4,15];
- getSumMore(...mySecondArray); // The sum is 25
- // Arrow functions
- let difference = (num1, num2) => num1 - num2; // expression
- document.write(`${difference(1,2)}<br />`); // -1
- // statemnt
- let mult = (num1, num2) => {
- let product = num1 * num2;
- return product;
- };
- document.write(`The result of mul = ${mult(10,3)} <br />`); // The result of mul = 30
- // Reduce
- let valArr = [1,2,3,4];
- let sumVal = valArr.reduce((a,b) => a + b); // let say we want to find the sume of the elements and return only 1 value
- document.write(`The result of reduce = ${sumVal} <br />`); // The result of reduce = 10
- // Filters
- let odds = valArr.filter(a => a % 2); // this also woks
- let evens = valArr.filter(a => a % 2 == 0);
- document.write(`${evens} <br />`); // 2,4
- //!!! we don't need to cycle trough
- for (let v of evens) {
- document.write(`${v} <br />`);
- }
- /*
- 2
- 4
- */
- // Map
- let doubles = valArr.map(v => v * 2);
- document.write(`${doubles} <br />`); // 2,4,6,8
- // Object literals
- function createAnimal(name, owner){ // You always have been able to do so
- return {
- name,
- owner,
- getInfo(){
- return `${this.name} is owned by ${this.owner}`
- },
- address : {
- street: "123 main streat",
- city: 'Pitsburg'
- }
- };
- }
- // make the difference
- // document.write(typeof {'Stoyan',"Cheresharov"} + "<br />"); //es6tut.js:38 Uncaught SyntaxError: Unexpected token ,
- // document.write(typeof {'Stoyan'} + "<br />"); //es6tut.js:38 Uncaught SyntaxError: Unexpected token }
- var spot = createAnimal("Spot", "Dug");
- document.write(`${spot.getInfo()}<br />`); // Spot is owned by Dug
- // as a difference The old style
- function createAnimalOld(name, owner){ // You always have been able to do so
- return {
- 'name': name,
- owner: owner,
- getInfo: function(){
- // return `${this.name} is owned by ${this.owner}`
- return this.name + ' is owned by ' + this.owner;
- },
- address : {
- street: "123 main streat",
- city: 'Pitsburg'
- }
- };
- }
- var barOldStyle = createAnimalOld('Bary', 'Stoyan');
- document.write(`${barOldStyle.getInfo()}<br />`); // Bary is owned by Stoyan
- document.write(`${Object.getOwnPropertyNames(spot).join(' ')} <br />`); // name owner getInfo address
- // 22:23 Destructoring
- let {name, owner} = spot; // We had the similar thing in PHP
- document.write(`Name: ${name} <br />`); // Name: Spot
- let {address} = spot;
- document.write(`Name: ${address.street} <br />`); // Name: 123 main streat
- // Destructoring arrays
- let favNums = [2.5435, .3543, 4.654];
- let[,,chaos] = favNums;
- document.write(`${chaos}<br />`); // 4.654
- let [,...last2] = favNums;
- document.write(`${last2}<br />`); // 0.3543,4.654
- // switch values without using 3-th variable
- let val1 = 1, val2 = 2;
- [val1, val2] = [val2, val1];
- document.write(`${val2}<br />`); // 1
- // Classes
- class Mammal {
- constructor(name){
- this._name = name; // protected automatic field
- }
- get name() {
- return this._name;
- }
- set name(name){
- this._name = name;
- }
- static makeMammal(name){
- return new Mammal(name);
- }
- // regular old methods
- getInfo(){
- return `${this._name} is a mammal`;
- }
- }
- let monkey = new Mammal('Fred');
- monkey.name = 'Mark';
- document.write(`Mammal: ${monkey.getInfo()} <br />`); // Mammal: Mark is a mammal
- let chipmunk = Mammal.makeMammal("Stoyan");
- document.write(`Mammal 2: ${chipmunk.getInfo()} <br />`); // Mammal: Stoyan is a mammal
- class Marsupial extends Mammal{
- constructor(name, hasPouch){
- super(name); // call the base super
- this._hasPouch = hasPouch;
- }
- get hasPouch() {
- return this._hasPouch;
- }
- set hasPouch(hasPouch){
- this._hasPouch = haspouch;
- }
- getInfo(){ // overriding the method
- return `${this.name} is a marsupial`;
- }
- }
- let kangaroo = new Marsupial('Paul', true);
- document.write(`It is ${kangaroo.hasPouch} that ${kangaroo.name} has a pouch!<br />`); // It is true that Paul has a pouch!
- document.write(`kangaroo: ${kangaroo.getInfo()} <br />`); // kangaroo: Paul is a marsupial
- document.write(`Mammal 2: ${chipmunk.getInfo()} <br />`); // Mammal 2: Stoyan is a mammal
- // conditional inheritance
- // Dynamic class
- function getClass(classType){
- if (classType == 1) {
- return Mammal;
- } else {
- return Marsupial;
- }
- }
- class Koala extends getClass(2){
- constructor(name){
- super(name);
- }
- }
- let carl = new Koala('Carl');
- document.write(`${carl.getInfo()} <br />`); // Carl is a marsupial
- // Symbols
- // let capital = new Symbol("State capital. This description is For debug purposes only."); // es6tut.js:363 Uncaught TypeError: Symbol is not a constructor(…)
- let capital = Symbol("State capital. This description is For debug purposes only.");
- let pennsylvania = {};
- pennsylvania[capital] = "Harrisburg";
- document.write(`The capital of Pennsylvania is : ${pennsylvania[capital]} <br />`); // The capital of Pennsylvania is : Harrisburg
- document.write(`Symbol description : ${capital.toString()} </br>`); // Symbol description : Symbol(State capital. This description is For debug purposes only.)
- // share Symbols
- let employNum = Symbol.for("Employee number");
- let bobSmith = {};
- bobSmith[employNum] = 10;
- let sallyMarks = {};
- sallyMarks[employNum] = 5;
- document.write(`Sally: ${sallyMarks[employNum]} Bob: ${bobSmith[employNum]} <br />`); // Sally: 5 Bob: 10
- // arrays
- let array1 = Array.of(1,2,3); // notice no new
- let array2 = Array.from("word");
- let array3 = Array.from(array1, (value) => value * 2);
- for (let val of array1){
- document.write(`${val} <br />`); // 123
- }
- /*
- 1
- 2
- 3
- */
- document.write(`${array1} <br />`); // 1,2,3 |
- document.write(`${array2} <br />`); // w,o,r,d |
- document.write(`${array3} <br />`); // 2,4,6
- // Set a set of values without duplication
- var randSet = new Set();
- randSet.add(10);
- randSet.add('word');
- document.write(`${randSet.has(10)} <br />`); // true
- document.write(`${randSet.size} <br />`); // 2
- randSet.delete(10);
- document.write(`${randSet.size} <br />`); // 1
- for (let val of randSet) {
- document.write(`${val} <br />`);
- }
- // Map is a collection of key => value pairs
- var randMap = new Map();
- randMap.set("key1", "First value");
- randMap.set('key2', "Second value");
- document.write(`${randMap.get('key1')}<br />`); // First value
- document.write(`${randMap.get("key2")}<br />`); // Second value
- document.write(`${randMap.size}<br />`); // Second value
- randMap.forEach(function(value, key) {
- document.write(`${key} ${value}<br />`);
- });
- /*
- key1 First value
- key2 Second value
- */
- // Promises - define code that is going to be executed later. They either susseed or family
- // They will have a state of fulfilled, rejected, pending, sdled???
- // Promise that is handled imediately
- var p1 = Promise.resolve('Resolve me');
- p1.then((res) => document.write(`${res}<br />`)); // Resolve me. the second method is option in case of failiar
- // promise that will execute after 2 sec
- var p2 = new Promise(function(resolve, reject){ // resolve will be replaced with whatever you get from the caller
- // window.setTimeout(function(){
- // do something
- // }, 2000);
- window.setTimeout(() => resolve('Resolve Me'), 4000);
- });
- p2.then((res) => document.write(`${res}<br />`)); // when this gets executed do whatever get from resolve
- // clear the screen in 2 secs and writes "Resolve Me"
- // promise can be fulfilled or rejected
- let randval = 18;
- var p3 = new Promise(function(resolve, reject){ // when the promise finishes will cal resolve or reject
- if (randVal == 6) {
- resolve('Good Value'); // calls the callback
- } else {
- reject('Bad value');
- }
- });
- p3.then(
- // res is an argument comming from the promise
- (res) => document.write(`The promise was fullfiled and it calls resolved with whatever I put here as a function ${res}<br />`),
- (rej) => document.write(`This function is called in case of rejection and rej gets its value as a formal or argument ${rej}<br />`)
- );
- // This function is called in case of rejection and rej gets its value as a formal or argument ReferenceError: randVal is not defined
- // Add catch to the chain to catch the exceptions
- let randVal = 18; // !!! it still works we have this variable declared above
- var p4 = new Promise((resolve, reject) => {
- if (randVal <= 17) {
- // resolve("Can't vote"); // calls the callback
- throw new Error("Can't vote");
- } else {
- resolve('Can vote');
- // reject('Bad value');
- }
- });
- p4.then((val) => document.write(`${val}<br />`))
- .catch((err) => document.write(`${err.message}<br />`)); // Can vote
- // alert("I am here!");
- console.log("I am here");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement