The Future is Now

Using ES6 in Your
Javascript Code Today

Ben Glassman

Email @ ben@vtdesignworks.com
CTO @ Vermont Design Works
Adjunct Professor @ Champlain College
Beer Geek @ City of Winooski

Interested in writing apps in React with ES6?
We are hiring front-end and back-end devs!

Start Using ES6 Today

Start Using ES6 Today

  • What is ES6
  • Browser Support & Tooling
  • Variables
  • Functions
  • Objects
  • Strings
  • Classes

What is
ES5
?

What is ES5?

A modest set of new APIs for existing types
Object.create/keys, String.trim, Array.map/reduce/some/forEach, JSON.parse/stringify

What is ES5?

Slow adoption model (waiting for browser support) even though most features could be used immediately via polyfills or shims

What is
ES6
?

What is
ES2015
?

What is ES6?

ES6 is a radical jump forward for the Javascript language New syntax, abstractions, behavior, types

Browser Support

Fair support in newest versions browsers
Edge, Current Chrome/Firefox/Safari

Browser/Platform Support

Newest Version of Browsers w/ % ES6 Features Supported (June 2016)

  • IE 11 15%
  • Edge 79%
  • Firefox 90%
  • Chrome 98%
  • Safari/iOS 53%
  • Android 29%
  • Node 93%

Full compatibility table

The Future Sucks

The
Future
is
Now
Nam
June
Paik

We have the
tools

We have the
transpiler

Transpilation

Transforming code written in one programming language
into code in another programming language

Transpilation

Transforming code written in ES6
into code in ES5

ES5 Platform/Browser Support
June 2016

Excellent Support in Current Browsers
IE 9+, SF 6+, FF 21+, CH 23+

  • IE9+ 85% (No strict mode)
  • Firefox 21+ 100%
  • Chrome 23+ 98%
  • Safari/iOS 96%
  • Android 98%

Full compatibility table

You put Javascript in   
You get Javascript out

Babel Usage: CLI


$ npm install --global babel
$ babel script.js --watch --out-file script-compiled.js
                    

Babel Usage: Build Tools

Babel integrates with your build tool of choice

  • Browserify
  • Webpack
  • Grunt
  • Gulp
  • jspm
  • RequireJS
  • & more

Full setup documentation

ES6 Variables

Control variable scope with let and const

Block scoping with let


// ES5
var hat = 'bowler';
for (var i = 0; i < 4; i++) {
    var hat = 'colander';
}
console.log(hat); // 'colander'
console.log(i); // 3
                    

// ES6
let hat = 'bowler';
for (let i = 0; i < 4; i++) {
    let hat = 'colander';
}
console.log(hat); // 'bowler'
console.log(i); // undefined
                    

Colliding variables with let


// ES5
var hat = 'bowler';
// do something
var hat = 'colander';
console.log(hat); // 'colander'
                    

// ES6
let hat = 'bowler';
// do something
let hat = 'colander'; 
// Error: Duplicate declaration
                    

Read-only variables with const


// ES5
var hat = 'bowler';
hat = 'colander';
console.log(hat); // 'colander'
                    

// ES6
const hat = 'bowler';
hat = 'colander'; 
// Error: hat is read-only
                    

ES6 Functions

Arrow Functions

Provide lexical (i.e. expected) value for the this variable.

Arrow Functions


// ES5
var app = {
    confirmText: 'Are you sure?', 
    init: function() {
        var _this = this; // Grrr!
        var handleConfirm = function(e) {
            e.preventDefault();
            var confirmed = confirm(_this.confirmText);
            if (confirmed) {
                window.location.href = e.target.href;
            }
        };
        $('a.confirm').click(handleConfirm);
    }
}
                    

Arrow Functions


// ES5
var app = {
    confirmText: 'Are you sure?', 
    init: function() {
        var handleConfirm = function(e) {
            e.preventDefault();
            var confirmed = confirm(this.confirmText);
            if (confirmed) {
                window.location.href = e.target.href;
            }
        }.bind(this); // Gnash!
        $('a.confirm').click(handleConfirm);
    }
}
                    

Arrow Functions


// ES6
const app = {
    confirmText: 'Are you sure?', 
    init: function() {
        var handleConfirm = (e) => {
            e.preventDefault();
            var confirmed = confirm(this.confirmText);
            if (confirmed) {
                window.location.href = e.target.href;
            }
        };
        $('a.confirm').click(handleConfirm);
    }
}
                    

Arrow Functions

Terse syntax for anonymous functions

Arrow Functions


// ES5
[1, 2, 3].filter(function(num) {
    return num > 2;
});

var items = [
    { id: 5, name: 'foo' }, 
    { id: 6, name: 'bar' }
];
items.map(function(obj) {
    return obj.id;
});
                    

// ES6
[1, 2, 3].filter((num) => num > 2);

var items = [
    { id: 5, name: 'foo' }, 
    { id: 6, name: 'bar' }
];
items.map(obj => obj.id);
                    

Default Parameters

You know... like in other languages.

ES5 Default Parameters


// ES5
function join(parts, separator) {
    var separator = separator || '-';
    // Doesnt allow falsy separator like ''
    return parts.join(separator);
}
join(['a', 'b', 'c']);
// 'a-b-c'
                    

ES6 Default Parameters


// ES6
function join(parts, separator = '-') {
    return parts.join(separator);
}
join(['a', 'b', 'c']);
// 'a-b-c'
                    

ES5 Variadic Functions


// ES5
function join(/* separator, part1, part2, partN */) {
    if (arguments.length < 2) {
        throw new Error('BAD INPUT');
    }
    var separator = arguments[0] || '-';
    var parts = Array.prototype.slice.call(arguments, 1);
    return parts.join(separator);
}
join(',', 'a', 'b', 'c');
// 'a,b,c'
                    

ES6 Variadic Functions
using rest parameters


// ES6
function join(separator = '-', ...parts) {
    return parts.join(separator);
}
join(',', 'a', 'b', 'c');
// 'a,b,c'
                    

ES6 Objects

Object Property Initialization


// ES5
var type = 'bowler';
var hat = {
    id: 5,
    type: type
};
console.log(hat.type); 
// 'bowler'
                    

// ES6
let type = 'bowler';
let hat = { 
    id: 5,
    type
};
console.log(hat.type); 
// 'bowler'
                    

ES5 Object Method Initialization


// ES5
var type = 'bowler';
var hat = {
    type: type,
    id: 5,
    doff: function() {
        console.log('I doff my '+this.type);
    }
};
                    

ES6 Object Method Initialization


// ES6
let type = 'bowler';
let hat = { 
    type,
    id: 5,
    doff() {
        console.log('I doff my '+this.type);
    }
};
                    

Object Destructuring


// ES5
var hat = {
    id: 5,
    type: 'bowler'
};
var type = hat.type;
console.log(type); // 'bowler'
                    

// ES6
let hat = { 
    id: 5,
    type: 'bowler'
};
const { type } = hat;
console.log(type); // 'bowler'
                    

Object Destructuring
with Defaults


// ES5
var hat = {
    id: 5,
    type: 'bowler'
};
var type = hat.type;
var size = hat.size || 'M';
console.log(type, size); 
// 'bowler', 'M'
                    

// ES6
let hat = { 
    id: 5,
    type: 'bowler'
};
const { type, size = 'M' } = hat;
console.log(type, size); 
// 'bowler', 'M'
                    

Object Destructuring
with Defaults & Rest Properties


// ES5: ?!?!?
                    

// ES6
let hat = { 
    id: 5,
    type: 'bowler'
};
const { type, size = 'M', ...other } = hat;
// other = { id: 5 }
                    

Object Destructuring for Arguments


// ES6
function doff({ type }) {
    console.log('I doff my '+type);
}
let hat = { 
    id: 5,
    type: 'colander'
};
doff(hat);
// I doff my colander
                    

Object.assign

Native $.extends


// ES6
let hat = { 
    id: 5,
    type: 'bowler'
};
let yourHat = Object.assign({}, hat, { id: 6 });
// hat = { id: 6, type: 'bowler' }
                    

ES7 Features

Babel also supports some ES7 features
with the same browser support!


$ babel script.js --optional es7.objectRestSpread
                    

ES7 Spread Properties

Sugar for Object.assign


// ES7
let hat = { 
    id: 5,
    type: 'bowler'
};
let yourHat = { ...hat, id: 6 };
// yourHat = { id: 6, type: 'bowler' }
                    

Template Strings

Expression interpolation, multi-line strings & more

Expression Interpolation


// ES5
var hat = {
    type: 'colander'
};
console.log(['I doff my ', hat.type, ' to you'].join(''));
// 'I doff my colander to you
                    

// ES6
var hat = {
    type: 'colander'
};
console.log(`I doff my ${hat.type} to you`);
// I doff my colander to you
                    

Multi-line Strings


// ES5
var message = 'I doff colander\n' + 
              'my futuristic hat choice\n' +
              'hangs low in respect';
                    

// ES6
var message = `I doff colander
my futuristic hat choice
hangs low in respect`;
                    

Tagged Template Strings
Custom Processing Logic


// ES6
let varDump = function(strings, ...values) {
    const parts = values.map((v, i) => {
       return `${strings[i]}${typeof v}(${v})`;
    });
    return parts.join('');
};
let hat = {
  id: 5,
  type: 'colander'
};
console.log(varDump`Hat id ${hat.id} is a ${hat.type}`);
// "Hat id number(5) is a string(colander)"
                    

New String Methods


// ES6
var hat = {
    type: 'colander'
};
hat.type.startsWith('col'); // true
hat.type.endsWith('er'); // true
hat.type.includes('and'); // true
                    

ES6 Classes

“Object-oriented programming is an exceptionally bad idea which could only have originated in California.”

– Edsger Dijkstra

ES6 Classes

Syntax mimics classical inheritance.

Implementation is prototypical inheritance.

ES5 Classes


// ES5
function Hat() {
    this.type = 'generic hat';
}
Hat.prototype = {
    doff: function() {
        console.log('I doff my '+this.type);
    }
};
var myHat = new Hat();
myHat.doff();
// I doff my generic hat
                    

ES6 Classes


// ES6
class Hat {
    constructor() {
        this.type = 'generic hat';
    }
    doff() {
        console.log('I doff my '+this.type);
    }
}
var myHat = new Hat();
myHat.doff();
// I doff my generic hat
                    

Inheritance


// ES6
class Colander extends Hat {
    constructor() {
        super(); // mandatory before using this
        this.type = 'colander';
    }
    // In the future, we doff twice
    doff() {
        super.doff();
        super.doff();
    }
}
var myHat = new Colander();
myHat.doff();
// I doff my colander
// I doff my colander
                    

ES5 Prototype Properties


// ES6
function Hat() {
}
Hat.prototype = {
    type: 'generic hat',
    doff: function() {
        console.log('I doff my '+this.type);
    }
};
var myHat = new Hat();
myHat.doff();
// I doff my generic hat
                    

ES7 Class Property Initializers


// ES7
class Hat {
    type = 'generic hat';

    // guaranteed lexical this
    doff = () => {
        console.log('I doff my '+this.type);
    }
}
var myHat = new Hat();
myHat.doff();
// I doff my generic hat
                    

More ES6 Features

  • Generators
  • Decorators
  • Promises
  • Iterables
  • Modules

Use ES6 Today

  • Its framework agnostic
  • Easy browser support with Babel
  • Improves code readability (const, object destructuring)
  • Decrease bugs (let/const, arrow functions)
  • Increase productivity (arrow functions, property/method initializers)
  • Reduce dependencies (Object.assign)
  • Embrace the future

The Future is Now

Thank You!
Mom, Dad, My Dog Trevor, The Johns Carmack & Romero

Ben Glassman

Email @ ben@vtdesignworks.com
CTO @ Vermont Design Works
Adjunct Professor @ Champlain College
Beer Geek @ City of Winooski

Interested in writing apps in React with ES6?
We are hiring front-end and back-end devs!

Resources