ECMAJavascript 6

home

Contents

18.1     es6 now, Feb 6, 2018

18.2     let, const to declare variables

        // lab 1: before es6, variable name is inside if statement
        // test with plunkr,  the output is emi
        // no scope sense

        if (true) {
            name = "emi"
        }
        console.log(`name is ${name}`)

        // lab 2: use let to declare a local variable
        if (true) {
            let name = "emi"
            console.log(`name is ${name})`    // emi
        }
        console.log(`name is ${name}`)        // empty, no access

        // lab 3: const 
        const rate = 0.99
        console.log("rate = " + rate)   // 0.99
        rate = 1.11    // assigment to a constant variable
            

18.3     arrow function

        // lab-1, arrow function, no return
        let add = (x,y) => x + y
        let result = add(2,3)
        console.log(`result is ${result}` )       // result is 5

        // lab-2, arrow function
        let add = (x,y) => {
                       let result = x + y
                       return result
                   }
        let result2 = add(2,3)
        console.log(`result2 is ${result2}` )      // result2 is 5

        // lab-3, demonstrate the terse with array filter function
        // ages is an array
        // array has filter function
        
        // the function argument is another function to test each array item
        // If the test is passed, the item will be appended into the result array.
        
        let ages = [32, 33, 16, 40]
        let adultAges = ages.filter(age => age >= 18)
        console.log(adultAges)    // [32, 33, 40]

        // lab-4, make this for the context of the object myPage
        var myPage = {
            id: "999888777",
            init: function() {
                document.addEventListener("click",
                        event => this.doSomething(event.type), 
                        false);
            },
            doSomething: function(type) {
                console.log("Handling " + type  + " for " + this.id);
            }
        };
        myPage.init()

        // in plunkr, type the code, run it, click the page,
        // in the developer tool
        //     the output is Handling click for 999888777


            

18.4 promise

A promise is a holder for a result(or a error) that will becomes available in the future,when the async call returns.

Before es6, jquery and callback are the solution for those async tasks.

// ------ lab-1 Promise and fetch ---------------------------------- <!DOCTYPE html> <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.29/browser.js"></script> <script type="text/babel"> const getUsersData = () => { return new Promise((resolves, rejects) => { const api = 'https://jsonplaceholder.typicode.com/users'; const request = new XMLHttpRequest(); request.open('GET', api); request.onload = () => { if(request.status === 200) { resolves(JSON.parse(request.response)); } else { rejects(Error(request.statusText)); } }; request.onerror = err => rejects(err); request.send(); }); }; getUsersData().then( data => { console.log(data) }, err => console.error( new Error('Cannot load space people') ) ); </script> <title>Promises</title> </head> <body> </body> </html>
        //  ------   lab-2    fetch   ----------------------------------
        //  replacing the related as below:
        const getUserDataWithFetch = () => 
            fetch('https://jsonplaceholder.typicode.com/users') 
                .then(res => res.json());
        getUserDataWithFetch()
               .then(data => console.log(data))
            

18.5 Manupulating data collection in client side

      note: This is NOT about sorting, filtering, formatting a data collection in database tier or web server tier.

        // es6 for of iteration --- array

        let employees = ["John", "Mary", "Ben"]
        for (let employee of employees){
                console.log(employee)
        } 
        
            - You don't deal with the index(inner state).
            - The employees can be one data part in a class Company.
        

        // for of ieration for es6 new class Set
        let colorArray = ["white", "red", "green", "red"]
        let colorSet = new Set(colorArray)       
        console.log(colorSet.size)        // 3,  a set has unique items
        console.log(colorSet.has("red"))  // true
        for (let color of colorSet){
          console.log(color)
        }

        // for of iteration for es6 new class Map
        let accountArray = 
          [
            ["accountNo", 3],
            [3, "account status"]
          ]
        let accountMap = new Map(accountArray)   

        console.log(accountMap.size)   // 2,  a set has unique items
        console.log(accountMap.get(3)) // account status

        for (let item of accountMap){
          console.log(item)            // ["accountNo", 3]
        }  

        // before es6, array method map
        // its function argument is an anonymous arrow function
     
        let arr = [2,4,6,8]
        let plus5 = arr.map(item => item + 10)
        console.log("plus5 = " + plus5)  // [12, 14, 16, 18]
  
        // before es6, array method filter
        // its function argument is an anonymous arrow function,
        //    when processing one item, if return true, it is selected.

        var ages = [12, 20, 26, 40]
        let adults = ages.filter(age => age >= 18)
        console.log(adults)     // [20, 26, 40]

        // before es6, array method sort

        // sort in alphabetical order

        var fruits = ["banana", "melon", "apple", "lemon"];
        fruits.sort(); 
        console.log(fruits)   //["apple, ""banana", lemon", "melon"]
        fruits.reverse()
        console.log(fruits)   //["melon", "lemon", "banana", "apple"]

        // sort in numeric order

        var scores = [33, 55, 11, 22, 44]
        scores.sort((a, b)=> a - b)
        console.log(scores)             // [11,22,33,44,55]
        scores.sort((a, b)=> b - a)
        console.log(scores)             // [55,44,33,22,11]
        
        
            - sort function's parameter is an anonymous arrow function
            - it is called compare function
            - if function body is a - b, it is in ascending order.
            - if function body is b - a, it is in descending order.
        


            

18.6 symbol, iterator, generator


        // lab-1:  create a iterator for array using well-known Symbol.iterator
         
        const arr = [1,4,2];
        const iter = arr[Symbol.iterator]();
        
            - Symobl is a new language type in javascript.
            - arr[Symbol.iterator] is a property for the array.
            - Symbol.iterator has been already implemented for iterator with default behaviors.
            - with (), to run it and create a iterator.
        
        console.log(iter.next()); // {value: 1, done: false}
        console.log(iter.next()); // {value: 4, done: false}
        console.log(iter.next()); // {value: 2, done: false}
        console.log(iter.next()); // {value: undefined, done: true}

        // lab-1x:  create a custom iterator
        // an array is iterable    
        // to custom the iterator, a bit different

        function makeIterator(array) {          // function
           var nextIndex = 0
           return {         // object
               next: function() {     // custom function
                        return nextIndex < array.length 
                            ? {value: array[nextIndex++], done: false} 
                            : {done: true};   // removing undefined
                         }
                      }
        }

        var it = makeIterator(['happy', 'lucky'])
        console.log(it.next().value)     // 'happy'
        console.log(it.next().value)     // 'lucky'
        console.log(it.next().done)      // true

        // automatical call. I do not know how to use for-of loop
        var it2 = makeIterator(array)
        for (var i = 0; i < 2; i++){
            console.log(it2.next())
        }

        // lab 2: Generator
        // A GeneratorFunction is a special type of function that works as a factory for iterators. 
        // A generator can has state information.
        // You can find fibonacci state demo in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators


        function* idMaker() {     
                 var index = 0;
                 while(true)
                      yield index++;
        }

        var gen = idMaker();                        //  create a iterator

        console.log(gen.next().value); // 0         //  call its method next
        console.log(gen.next().value); // 1
        console.log(gen.next().value); // 2
        // ...

        // lab 3: iterable
        // an object is not iterable by default
        // The following code to make the object iterable.
        // adding the property with key Symbol.iterator, a well-known iterator
        // and set it value to a generator

        var myIterable = {};

        myIterable[Symbol.iterator] = function* () {
                 yield 1;
                 yield 2;
                 yield 3;
        };

        // for of loop will call iterator's next function
        // call the iterator next method for each
        for (let value of myIterable) { 
                 console.log(value); 
        }
        // 1
        // 2
        // 3

        // spread operator will call iterator's next function ALSO.
        console.log([...myIterable]);       // [1, 2, 3]
            

18.7 class in ES6

        class AgencyEmployee {             // class declaration
			constructor(name, salary) {
				this.name = name
				this.salary = salary
			}
			getSalary(){                   // method to retrieve its property         
			  return this.salary
			}
			
        }	
        const emp1 = new AgencyEmployee("tairo", 35000)  // object instantiation
        console.log(emp1)       // AgencyEmployee{name: "tairo", salary: 35000}
        console.log(emp1.name)           // tairo
        console.log(emp1.getSalary())    //35000

        class Agent extends AgencyEmployee {                 // inheritance			
			        constructor(name, salary, commission = 0) {  // class declaration
				        super(name, salary)                  // default function parameter
				        this.commission = commission				
			        }
			        calculatePay(){                           // method decaration
			          return super.getSalary() + this.commission
			        }
        }
        const agent007 = new Agent("emi", 40000, 1500)        // object instantiation
        console.log(agent007)     // Agent {name: "emi", salary: 40000, commission: 1500}
        console.log(agent007.commission)      // 1500
        console.log(agent007.calculatePay())  // 41500

        console.log(typeof AgencyEmployee)           // function
        console.log(typeof Agent)                    // function
        console.log(typeof emp1)                     // object
        console.log(typeof agent007)                 // object
        console.log(emp1 instanceof AgencyEmployee)  // true
        console.log(agent007 instanceof Agent)       // true

        // default function parameter, ES6, commission not provided
        const agent008 = new Agent("wiwi", 10000)    // default function parameter
        console.log(agent008.calculatePay())         // 1000