Tag Archives: ecmascript

Psyched about ES6

Making a note of the upcoming features, hopefully I will be able to remember it until it’s actually implemented across all browsers (thumbs up for Mozilla having implemented a lot of it into Firefox already).
 
 
Block scoping & function declarations

   
   function myFn () {

       if(true) {
           var a = 1;
           let b = 2;
           
           function myFn2 () {
              // ...
           }
       }
       
       console.log(a); // 1
       console.log(b); // ReferenceError: b is not defined
       myFn2(); // ReferenceError: fn is not defined
   }  
 

 
 
Constants

    
    const a; // SyntaxError: const declarations must have an initializer
    const a = 1;
    a = 2; // SyntaxError: Assignment to constant variable

    // Note that 'const' variables are block scoped / lexical scoped just as 'let' variables are.
 

 
 
Default parameters


    function myFn (x, y = 2, z = x * 2) {
        return [x, y * x, z];
    }

    myFn(5); // [5, 10, 10]
 

 
 
Destructuring

 
    var [x,y] = [1,2]; // x : 1, y : 2
    [x,y] = [y,x]      // x : 2, y : 1
 

 
 

Multiple return values, spread, rest parameters

   
   function myFn(title, ...vars) {
       return [...vars]; 
   }

   myFn(1,2,3,4,"hoax"); // [2,3,4, "hoax"]
 

   function myFn2(a,b,c) {
       return [a,b,c];
   }

   myFn2(1, ,3); // [1,3]
   

   function myFn3() {
       return [1,2,3];
   }

   var [a, ,c] = myFn3(); // a : 1, c : 3
  

   function myFn4(a,b,c) {
       return b;
   }

   var arr = [1,2,3];
   
   myFn4(...arr); // 2
   

 
 
Collections

  
   var mySet = new Set();
   mySet.add("Hollah");
   mySet.has("Hollah"); // true
   mySet.delete("Hollah");
   mySet.has("Hollah"); // false

   var myMap = new Map();
   myMap.set("Item", 5);
   myMap.set("Horse", "Pinto");
   myMap.get("Item");

   for( var [thing, value] of myMap ) {
        console.log(thing + ": " + value);
   }

   myMap.delete("Item");
   myMap.has("Item"); // false   
  

 
 
Modules

  
   // helpers.js

   export fnA() {
     console.log("fnA!");
   }

   export fnB() {
     console.log("fnB!");
   }
  
  
   // main.js

   import { fnA, fnB } from 'helpers';

   fnA();
   fnB();
  

 
 
Array comprehension

   
   var temp = [ 0, 37, 100 ];
   [t + 273 for (t of temp)]; // [273, 310, 373]

   // Excellent "Cluedo" example from TutsPlus..
   
   var suspects = ["Miss Scarlet", "Colonel Mustard"],
       weapons = ["Candlestick", "Dagger"],
       rooms = ["Kitchen", "Ballroom"];
 
   [(console.log(s + " with a " + w + " in the " + r)) for (s of suspects) for (w of weapons) for (r of rooms)];

   // Miss Scarlet with a CandleStick in the Kitchen
   // Miss Scarlet with a Candle Stick in the Ballroom
   // Miss Scarlet with a Dagger in the Kitchen
   // ...