What’s new JavaScript 2015/es6 (short summary)

  • let – block scope; no hoisting
  • const
  • Blocked scoped functions
    {
        function foo () { return 1 }
        foo() === 1
        {
            function foo () { return 2 }
            foo() === 2
        }
        foo() === 1
    }
    
  • Destructuring
    let foo = ["one", "two", "three"];
    
    let [one, two, three] = foo;
    console.log(one); // "one"
    console.log(two); // "two"
    console.log(three); // "three"
    
    //swapping
    let a = 1;
    let b = 3;
    [a, b] = [b, a];
    console.log(a); // 3
    console.log(b); // 1
    
    
    var expense = {
      type: 'Business',
      amount: '$40'
    }
    const {type, amount} = expense;
    
    //Or use in functions:
    function({type, amount}){}
    
    
  • Defaults

    let hasDefaults = function(something = "default"){
    console.log(something); //default
    }
    
  • Rest/Spread

    Rest:
    function sortRestArgs(...theArgs) {
      var sortedArgs = theArgs.sort();
      return sortedArgs;
    }
    
    console.log(sortRestArgs(5,3,7,1)); // shows 1,3,5,7
    
    Spread:
    const defaultColors = ['red', 'green'];
    const extraColors = ['orange', 'blue'];
    
    [...defaultColors, ...extraColors]
    
    
  • Template literals

    var a = 5;
    var b = 10;
    console.log(`Fifteen is ${a + b} and\nnot ${2 * a + b}.`);
    // "Fifteen is 15 and
    // not 20."
    
  • Arrow Functions

    let add = (a,b) => a+b;
    let sum = add(1,2);
    

    Also makes ‘this’ behave as you would expect it to behave.

  • Iterators and Generators
    for(let value of ["a", "b", "c"]){
        console.log(value)
    }
    // "a"
    // "b"
    // "c"
    
    function* idMaker(){
      var index = 0;
      while(true)
        yield index++;
    }
    var gen = idMaker();
    
    console.log(gen.next().value); // 0
    console.log(gen.next().value); // 1
    console.log(gen.next().value); // 2
    //Or
    for(let value of idMaker()){
        console.log(value)
    }
    
    
  • New Data Types

    var myMap = new Map();
    myMap.set(0, "zero");
    myMap.set(1, "one");
    for (var [key, value] of myMap) {
      console.log(key + " = " + value);
    }
    // Will show 2 logs; first with "0 = zero" and second with "1 = one"
    
    
    var mySet = new Set();
    mySet.add(1);
    mySet.add(5);
    mySet.add("some text");
    var o = {a: 1, b: 2};
    mySet.add(o);
    
    mySet.has(1); // true
    mySet.has(3); // false, 3 has not been added to the set
    mySet.has(5);              // true
    mySet.has(Math.sqrt(25));  // true
    mySet.has("Some Text".toLowerCase()); // true
    mySet.has(o); // true
    
    mySet.size; // 4
    
    mySet.delete(5); // removes 5 from the set
    mySet.has(5);    // false, 5 has been removed
    
    var wm1 = new WeakMap(),
        wm2 = new WeakMap(),
        wm3 = new WeakMap();
    var o1 = {},
        o2 = function(){},
        o3 = window;
    
    wm1.set(o1, 37);
    wm1.set(o2, "azerty");
    wm2.set(o1, o2); // a value can be anything, including an object or a function
    wm2.set(o3, undefined);
    wm2.set(wm1, wm2); // keys and values can be any objects. Even WeakMaps!
    
    ar ws = new WeakSet();
    var obj = {};
    var foo = {};
    
    ws.add(window);
    ws.add(obj);
    
    ws.has(window); // true
    ws.has(foo);    // false, foo has not been added to the set
    
    ws.delete(window); // removes window from the set
    ws.has(window);    // false, window has been removed
    
    
  • Modules

    //a.js:
    export let a ={};
    export let b =function(){};
    
    //c.js:
    import {a,b} from c
    
  • Promises

        var p1 = new Promise(        
            function(resolve, reject) {
                window.setTimeout(
                    function() {
                        resolve(42);
                    }, Math.random() * 2000 + 1000);
            });   
        p1.then(
            function(val) {           
            })
        .catch(
            function(reason) {
                console.log('Handle rejected promise ('+reason+') here.');
            });
    
    //With fetch:
    fetch(url)
      .then(response => response.json())
      .then(data => console.log(data));
    
  • Class, constructors
  • 
    class Test {
      constructor({someProperty}){}
      method(){}
    }
    
    class SubTest extends Test{
      constructor(options){
        super(options);
      }
      subMethod(){}
    }
    
  • Array Helper methods
    forEach
    map
    filter
    find
    every
    some
    reduce
    

    Examples:

    let colors = ['red', 'blue', 'green'];
    colors.forEach(c => console.log(c)); 
    
    let numbers = [1, 2, 3];
    let doubled = numbers.map(c => c * 2);
    let sum = numbers.reduce((sum, number) => sum + number, 0)
    
    let divisibleByTwo = numbers.filter(c => c % 2 === 0);
    let allDivisibleByTwo= numbers.every(c => c % 2 === 0);
    let someDivisibleByTwo= numbers.some(c => c % 2 === 0);
    
    
    let users = [ {name: 'Jay'},{name: 'May'},{name: 'Jay'} ]
    let jay = users.find(u => u.name === 'Jay')
    
    
  • Enhanced Object Literals

    function test(someValue)
    	{
        return {
          someValue: somevalue,
          someFunction: function(){}
     }
    
    Is now equivalent to 
      
     function test(someValue)
    	{
        return {
          someValue,
          someFunction(){}
     }
    
    
    

Some great resources on es6 – https://developer.mozilla.org and http://es6-features.org/

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.