14 luglio 2019

javascript ES6 ES2015

const

const myVar = 'value';
myVar = 'value2'; // error


let

var myVar = 'value';
if( myVar ){
    let myVar = 'value2';
    console.log(myVar);  // 'value2'
}
console.log(myVar);  // 'value'


String Template

let myHtml = `<div>${myVar}</div>`; // ` -> back tick character
let myTemplate = `
    <div>
        <span>${var1}</span>
        <span>${var2}</span>
    </div>
`;


Default values

function myFunction(par='some value'){
     // code
}
var defaultValue = 'value';
function MyFunction2(par=defaultValue){
    // code
}


Arrow function

let add5 = par1 => par1+5;
let sum = (par1, par2) => par1 + par2;
let myFunc = (par1, par2) => {
    if(par1<=0){
        par1 = 1;
   }
   return par1*par2;
}
let myObj = {
    myMeth: function(){   
         // code
   }
   myMeth2: function(){
         setTimeout(function(){
              this.myMeth(); // ERROR! function not preserve scope
        }, 1000);
   }
   myMeth2: function(){
        setTimeout( ()=>{
            this.myMeth();  // scope is myObj
        },1000);
   }
}

Destructuring

let obj = {k1:v1, k2: v2};
let {k1, k2} = obj;
console.log(k1, k2);
let myFunc = ({k1}) => console.log(k1);
let arr = ['first', 'second', 'third'];
let [firstItem] = arr;
let [,, thirdItem] = arr;

Object Literal Ehancement

let var1 = value1;
let var2 = value2;//rest is array without first item
let obj = {var1, var2}; //obj= {var1:value1, var2:value2}
let myFunc = function(){  
     return this.var1;
};
let obj2 =  {var1, var2, myFunc};
let obj3 = {
    prop1,
    prop2,
    myMeth(){
        //code
   }
}

Spread Operator

let arr1 = [v1, v2, v3];
let arr2 = [v4, v5, v6];
let arr3 = [...arr1, ...arr2]; //arr3 = [v1, v2, v3, v4, v5, v6];
let [last] = arr.reverse(); //array altered
let [last] = [...arr].reverse(); 
let [first, ...rest] = arr; //rest is array without first item
let obj = {k1:v1, k2:v2};
let prop = value;
let obj2 = {...obj, prop};

Promise

const getUsers = count => new Promise(
    (resolves, rejects) => {
         const url = `http://myapi/user/?limit:${count}`;
         const req = new XMLHttpRequest/(;
         req.open('GET', url);
         req.onload = () =>  req,status == 200 ? 
                            resolves(JSON.parse(req.response)).results :
                            reject(Error(req.statusText));
         req.onerror = (err) => reject(err);
         req.send();
   }
);

getUsers(10).then(
         users=>console.log(users), 
         err => console.error(err)
     );
getUsers(10)
    .then(users=>console.log(users))
    .catch(err=>console.log(err));


Class


class MyClass {
    constructor(par1, par2){
        // code
    }
    myMeth(){
        // code
    }
}
class MyClass2 extends MyClass{
    constructor(par1, par2, par3){
        super(par1, par2);
        // code
    }
    myMeth2(){
        // code
    }

}


Module

Module -> file

file1.js
export const myFunc = (par1) => par1+5;
export const myFunc2 = (par2) => par2^2;

file2,js
export const default myVar = 5;

file3.js
import {myFunc, myFunct2} from "./file1";
import {myVar} from "./file2";

alias
import {myFunc as f1, myFunct2 as f2} from "./file1";
all
import * as f from "./file1"

NodeJS (Common js)

file1.js
module.exports = {myFunc, myFunct2};
file3.js
const {myFunc, MyFunc2} = require("./file1");