Exploring Es6

Joe Buza

Features

  • Let & Const
  • Template Strings
  • Classes
  • Arrow functions
  • Default Arguments
  • Rest + Spread
  • Destructuring

Let vs Const vs Var

Let Const Var
block scoped block scoped global to function
mutable immutable  mutable

Let

 

  • Signals that a variable might be reassigned

  • Doesn't create a property on the global object

// top level program
var a = 10;
let b = 20;
console.log(this.a) // global
console.log(this.b) // undefined

Const

 

  • Signals that the Identifier can not be reassigned

  • recommended for normal use

  • must be initialized

const h;     // invalid
h = "hello"; // invalid

const h = "hello";    // valid
const w = h;         // Error

Var

 

  • signals a variable may or may not be assigned

  • signals a variable may or may not be used in the entire function

  • gives the weakest signal out of 'let' and 'const'

function hello(){
    var h = "hello";        //same 
    if(true){
        var h = "world";    // same
        console.log(h)     // world
    }   
    console.log(h)         //world

}

function hello(){
    let h = "hello";        //different 
    if(true){
        let h = "world";    // different
        console.log(h)     // world
    }   
    console.log(h)         //hello

}

'var' vs 'let'

Template Strings

  • enclosed by grave accents ``
  • multi-line strings do not require \n
  • expression interpolation

Grave Accents``

Es5

"String text"

Es6

`String text`

Multiline Strings

Es5

console.log("hello\n"+
"world")

//output
hello
world

Es6

console.log(`hello
world`);

//output
hello
world

Expression Interpolation

Es5

var a = 1;
var b = 2;
console.log("Sum "+(a + b)+".");

//output
Sum 3.

Es6

var a = 1;
var b = 2;
console.log(`Sum ${a + b}.`);

//output
Sum 3.

Class

syntatic sugar over Js's prototype based inheritance

 

  • Defining a Class
  • Class methods
  • Static methods
  • Inheritance

Defining Classes

Es5

function Animal(name){
    this.name = name;
}
Animal.prototype.getName = function(){
    return this.name;
}

Es6

class Animal{
    constructor(name){
        this.name = name;
    }
    get getName(){
        return this.name;
    }
}

Class syntax

class declaration

class Animal{
    constructor(name){
        this.name = name;
    }
    get getName(){
        return this.name;
    }
}

class expression

//unnamed
var Animal = class {
    constructor(name){
        this.name = name;
    }
    get getName(){
        return this.name;
    }
}

//named
var Animal = class Animal{
    constructor(name){
        this.name = name;
    }
    get getName(){..}
}

Class Methods

Es5

function Animal(name){
    this.name = name;
}
Animal.prototype.getName = function(){
    return this.name;
}

Es6

class Animal{
    constructor(name){
        this.name = name;
    }
    get getName(){
        return this.name;
    }
}

Static Methods

Es5

function Math(){
}
Math.sqrt = function(num){
    return num * num;
}

Es6

class Math{
    static sqrt(num){
        return num*num;
    }
}

use 'static' key world

Inheritance

Es5

function ClassA(){
}

var ClassB = Object.create(ClassA.prototype);
ClassB.prototype.constructor = ClassB;

Es6

class ClassA{
}

class ClassB extends ClassA{
}

use 'extends' key world

Arrow function

  • shorter functions
  • non binding to own 'this', 'arguments' or 'super'
  • suited for non methods
  • anonymous

Shorter functions

Es5

['a','b'].forEach(function(item){
    console.log(item);
});

Es6

['a','b'].forEach((item) => {
    console.log(item);
});

Advanced Syntax

  • Paranthesis optional when there's one paramater
function increment(i){
    return i++;
}
var increment = i => i++;
  • Paranthesize body to return object

=>

function toObj(a,b){
    return {
        a:a,
        b:b
    };
}
var toObj = (a,b) => ({
    a:a,
    b:b
});

=>

Non bind to 'this'

// Bad
function Incrementer(){
    this.counter = 0;
    setInterval(function(){
        console.log(++this.counter);
    },1000);
}

var i = new Incrementer();
 // Logs NaN
// Fix
function Incrementer(){
    var self = this;
    self.counter = 0;
    setInterval(function(){
        console.log(++self.counter);
    },1000);
}

var i = new Incrementer();
//logs 1, 2, 3, 4
// Best
function Incrementer(){
    this.counter = 0;
    setInterval(() => console.log(++this.counter),1000);
}
var i = new Incrementer();
//logs 1, 2, 3, 4...

1

2

3

Non bind to 'arguments'

// has own arguments
function plusOne(){
    console.log(arguments[0] + 1);
}
plusOne(1) //2 
// no own arguments 

var plusOne = () =>  console.log(arguments[0] + 1);
plusOne(1) //undefined 

Default Arguments

Used when an argument is either omitted or undefined.

'null' is a valid value.

Basics

Es5

function Person(firstName, lastName){
    this.firstName = firstName || "Joe";
    this.lastName = lastName || "Johnson";
}

Es6

function Person(firstName = "Joe", lastName = "Johnson"){
    this.firstName = firstName;
    this.lastName = lastName;
}

Objects 

function Person({
    firstName = "Joe",
    lastName = "Johnson"
   } = {}){
    this.firstName = firstName;
    this.lastName = lastName;
}
function Person(config){
    config = config || {};
    
    this.firstName = config.firstName || "Joe";
    this.lastName = config.lastName | "Johnson";
}

Es5

Es6

Rest/Spread '...'

  • replace 'arguments'
  • concatenation
  • push onto list
  • destructuring

Use cases:

Replace 'Arguments'

function printAll(){
    // get all arguments
    var args = Array.prototype.slice.call(arguments);
    console.log(args.join(', '));
}

printAll('print','hello','world');
// "print, hello, world"
function printAll(...args){/*using as rest*/
    console.log(args.join(', '));
}

//or 

var printAll = (...args) => console.log(args.join(', '));

printAll('print','hello','world');
// "print, hello, world"

Es5

Es6

Concatenation

var more = [3,4];
[1, 2].concat(more)
// [1, 2, 3, 4]
const more = [3, 4];
[1,2,...more];
// [1, 2, 3, 4]

Es5

Es6

Push

var groceryList = ['bread','milk'];
groceryList
    .push.apply(groceryList,['eggs', 'cereal']);
var groceryList = ['bread','milk'];
groceryList
    .push(...['eggs','cereal']);

Es5

Es6

Destructuring

var groceryList = ['bread','milk','eggs'];
var bread = groceryList[0]; // bread
var rest = groceryList.slice(1); // ['milk','eggs']
const groceryList = ['bread','milk','eggs'];
const [bread, ...rest] = groceryList; 

bread // 'bread'
rest// ['milk','eggs']

Es5

Es6

Destructuring

  • Object destructuring
  • Array destructuring

Use cases:

Convinient way of extracting data with variables

Object destructuring

const user = { first: 'Jane', last: 'Doe', age:28 };
const {
    first: f, // f = 'Jane'
    last: l,  // l = 'Doe'   
    age:a    // a = 28
} = user;



const user = { first: 'Jane', last: 'Doe', age:28 };
const {
    first,    // first = 'Jane' 
    last,     // last = 'Doe' 
    age      // age = 28
} = user;


{prop} is short for {prop: prop}

Array destructuring

const alph = ['a','b','c'];
const [a,b,c] = alph;
// a = 'a', b = 'b', c = 'c'


const url = 'https://www.google.com/search?q=url';
const [site,protocol,hostname,pathname,search] = 
/^(http[s]?):\/{2}([^\/\s]+)\/?([^\?]+)(.*)$/ig.exec(url);

console.log(`
	SITE => ${site}
	PROTOCOL => ${protocol}
	HOSTNAME => ${hostname}
	PATHNAME => ${pathname}
	SEARCH => ${search}
`);

Advanced

Resources

Questions?

Es6

By Joe Buza

Es6

Es6 is the 6th edition of ECMAScript, standardized in 2015. This slides will go through some of the new features introduced.

  • 1,213