Why ES6 is the best thing since bread.slice() – && how to jump in and never look back – Damon Muma, BA HSSC URR MOGA TM



Why ES6 is the best thing since bread.slice() – && how to jump in and never look back – Damon Muma, BA HSSC URR MOGA TM

0 0


es6talk

Slide deck for my presentation on ES6: Why ES6 is the best thing since bread.slice() && how to jump in and never look back

On Github thedamon / es6talk

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...

Show of Hands: -who uses javascript in their job? knows about ES6? tried it? -at work, -at home on personal projects, at work on personal projects -have you used it in production?

Outline

JavaScript: Not just for theatre & coffee lovers! What and why is ES6 Features in ES6? How is to ES6? 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...
Still looking up many properties to see if it works in your supported browsers Still weird inconsistencies and eccentricities Bit of a the wild west out there.

An S? Seriously?

ECMAscript 6 / ECMAscript 2015

Or as I like to call it: a pile of adorable kittens.

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
  • 🏢 > 🍝
How many ppl use a module loader/bundler right now? CommonJs? RequireJS? InvocationFUnctionAsyncPrototype Pattern? IT's all a bit easier with modules. Modules are the official way of getting functionality from one file into another. We should all be doing this.

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...'])

Remember how so many people complain that javascript isn't a real programming language because it doesn't have classes? Even if you don't use them, it will make you feel better knowing that they're there.

But it's really just prototypal inheritance

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!
        
In the spirit of javascript, these can be any value... like a function!

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'];
}
        
Kind of like destructuring.

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
        
CPN: Make sure these are predictible.

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!

Why ES6 is the best thing since bread.slice() && how to jump in and never look back