Why ES6 is the best thing since bread.slice()

&& how to jump in and never look back

Damon Muma,
BA HSSC URR MOGA TM

Senior Front-End Developer, User Experience Design & Video, Digital Services, London Life

@thedamon

E to the C to the M to the A to the...

Outline

  1. JavaScript: Not just for theatre & coffee lovers!
  2. What and why is ES6
  3. Features in ES6?
  4. How is to ES6?
  5. Promise: No Car Analogies

So... Javascript.

ES5...ish

  • Many confusing solutions for modularizing code
  • Many confusing solutions for doing classes/inheritence/prototypes
  • Does this work in my supported Browsers?
  • WEIRD syntax
  • Testing if things exist if typeOf null blah blah

//install
[4] * [4] // 16
[] * [] // 0
[] * {} // NaN
[4, 4] * [4, 4] // NaN
({} * {}) // NaN
  

Fuck it, gimme 241.59 KB of jQuery

  • A lot of weird things about javascript, especially with IE8 involved.
  • Drop IE8, you can at least use ES5
  • But still...

An S? Seriously?

ECMAscript 6 / ECMAscript 2015

JS Goes Evergreen

  • "2015" โฌ…๏ธ ๐Ÿ“œ to the Browsers
  • ๐ŸŒฑ Living Standard
  • Stay current. Adapt to Trends, Best Practices

Ecma

"Ecma International is an industry association founded in 1961, dedicated to the standardization of information and communication systems."
  • Not WHATWG etc
  • Unrelated to the Browser API (document.anyFunction(), fetch, etc)

What's Inside ES6?

Promises

  •  
  •  
  •  
  •  

Modules

  • Like Require.js/Browserify, etc
  • Official implementation
  • Dependency Management
  • Separation of Concerns
  • ๐Ÿข > ๐Ÿ

Export


//tinyPiglet.js

export const numEars = 2;
export default rubTummy function(){
  return "squeak!";
}
privateMethod = function(){
  return "well I never!";
}

//or
export {numEars, rubTummy}
        

Import


import {rubTummy, numberOfEarsOnAPiglet as numEars} from "tinyPiglet.js";
rubTummy(); //"squeak!"
console.log(numEars); //2

import * as piglets from "tinyPiglet.js"; //everything
piglets.rubTummy() //"squeak"!

import "tinyPiglet.js"; //side-effects only

import tinyPiglet from "tinyPiglet"; //default import
        

That's it!...?

  • No official module bundler (need jspm, webpack, browserify, etc)
  • Official syntax relies on separate files (HTTP2!!)
  • Use this: NOW

Classes!

  • Shut up, Java.
  • Prototypal Inheritance
  • Official Implementation
  • Classes > _.sample(['Prototype','Module', 'Revealing Module', 'etc...'])

import { cuteMeatAnimal } from 'cuteMeatAnimal';

class tinyPiglet extends cuteMeatAnimal {
  export const numEars = 2;

  constructor(){
    console.log('Stumble in and roll about on the floor.');
  }

  export default static rubTummy function(){ //Static: tinyPiglet.rubTummy
    return "squeak!";
  }
  privateMethod = function(){ //instance: new TinyPiglet().privateMethod()
    return "well I never!";
  }
}
        

That's it!

  • Use 'em!

Syntax stuff!

var, let, and const

  • var is weird, get rid of it.
  • let does not wander into parent scope. Good kitty! ๐Ÿ˜ธ
  • const can never be reassigned (it can change!)

var cat, toys = [], scritchesPerMinute;

let myCatsMood = 'cheerful';
const myCatsDisdainForMe = 'epic';
myCatsDisdainFormMe = 'gone!!' // ERROR!
        

Default Function Parameters

You maay have seen this before in another language...


function feedCat(
  food = 'catfood', 
  amount = function(){Math.random()},
  foodBrand = food + 'Co'
){
  if (food === 'human') callPolice();
}
feedCat() //will have defaults!
        

Arrow => Functions

  • Retain this from parent (no self or .bind()
  • implicit returns
  • Great for functional stuff like .map(), .filter(), .reduce().

//ES5ish
function(number) {
  return number % 2;
}

//ES6!!!
number => number % 2

(parameters) => {} // braces will *remove* implicit return
        

Template Literals

  • LITERALLY THE BEST! ๐ŸŽบ
  • Removes much of the need for non-native templating engines

//ES5ish
var example = 'This' + fetchCompliment() + 'string can go \
to another line and keep going'

//ES6!!!
let example = `This ${fetchCompliment()} string can go 
to another line and keep going`;
        

Promises

  •  
  •  
  •  
  •  

Objects and Arrays!

...spread and rest...

Spread is like a cross section of an array.


let partsToPet = ['back', 'tummy', 'tail']
petTheseParts(...partsToPet); 
//petTheseParts('back', 'tummy,', 'tail')

//Trick! quickly convert an object or collection to an array
[...document.querySelectorAll('')].forEach{...}

//or array building:
let foo = [2, 3, 4];
console.log(1, ...foo, 5) // '1 2 3 4 5'
        

Rest is not sleep ๐Ÿ˜Ÿ. PHP calls this the 'splat' operator๐Ÿ’ฆ.


//a flexible number of parameters
function petTheseParts(...parts){
  console.log(parts) //['back', 'tummy', 'tail'];
}
        

Destructuring ๐Ÿ’ฃ

Pull things out of an array


//response.kittens.thisKitten = {name: 'Smuggler'}
let {name, hairColour, favouriteSpot = 'myChair'} 
  = response.kittens.thisKitten;
name //"Smuggler" vs console.log(response.kittens.thisKitten.name)
hairColour //undefined
favouriteSpot //myChair
        

Destructuring ๐Ÿ’ฃ

You can rename what you extract but it's backwards ๐Ÿ”„


let {name: nameOfTheKittenIWillPet} = response.kittens.thisKitten;
name //undefined
theNameOfTheKittenIWillPet //Smuggler

//function parameter defaults when you're CALLING them?
shooCat(favouriteSpot = 'keyboard');

//or this ridiculousness:
var { x: { y: { z: w } } } = o1;
        

Object.assign() ๐Ÿ˜ƒ

This one is pretty straightforward, but awesome!


function updateKitten(newKitten){
  Object.assign({}, defaultKitten, currentKitten, newKitten);
}
let currentKitten = {favouriteToy: 'packing peanuts'}
inspectKitten(currentKitten);

updateKitten(currentKitten, {favoriteToy: 'my soft, mushy fingers'});
        

Computed Property Names (CPN?) ๐Ÿ—


{
  [surprisePropertyName()]: 'uuuuhh... 7?',
  ['theHolySwordOf' + myName]: swordStats
}
        

Property Value Shorthands (PVS?) ๐Ÿฐ


Object.is({ name }, {name: name}); //true
        

But Wait There's More!

  • promises
  • generators
  • maps
  • weak maps
  • sets
  • symbols
  • proxies
  • iterators
  • reflection

ES2016

  • Decorators
  • ::bind operator
  • Array.includes()
  • Rest and Spread for object properties

Using ES6

  • Browser Support ๐Ÿ”—
  • Transpiling
  • Transpiling
  • Transpiling

Babel

  • ES6+ polyfills via transpiling
  • Integrates with any build system
  • Configurable
  • Just launched a BNV 6 (Big New Version)
  • de facto Standard (โšฐ Traceur)

//install
$ npm install --save-dev babel-loader babel-core
        

Webpack


//project config:
module: {
  loaders: [
    { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader"}
  ]
}

//or per file:
var Person = require("babel!./Person.js").default;
        

Grunt


$ npm install --save-dev grunt-babel
        

grunt.initConfig({
  "babel": {
    options: {
      sourceMap: true
    },
    dist: {
      files: {
        "dist/app.js": "src/app.js"
      }
    }
  }
});

grunt.registerTask("default", ["babel"]);
        

And everything in between



And yes, this does all assume you're using NPM for package management.

So Why ES6?

  • easier to write
  • easier to read*
  • easier to not use jQuery
  • native โˆด smaller (eventually)
  • standardizing practices
  • getting used to change

Resources

Thank You!