Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ES6 - Angular Meetup Hamburg 2017-01-11

ES6 - Angular Meetup Hamburg 2017-01-11

ES6 is among us now and it introduced many new useful features, which makes solving typical everyday JavaScript challenges a lot easier. Let’s go through real life examples to create code that is dynamic, robust and maintainable.
Warning: This talk may contain traces of Arrow Functions, Template Strings, Destructuring, Proxies, Generators, Iterables, Classes, Promises, Sets, Maps and Functional Programming.

Avatar for Kim Hogeling

Kim Hogeling

January 11, 2017
Tweet

More Decks by Kim Hogeling

Other Decks in Programming

Transcript

  1. ES6

  2. Legend • const and let • Arrow functions • Extended

    parameter handling • Template literals • Enhanced object properties • Destructuring • Modules • Classes • Promises • Async Await • Proxy • Linear Data Flow • Generators • Online Ressources
  3. for (var i = 0; i < 5; i ++)

    { setTimeout(() => console.log(i), 1) } console.log(i) 5 5 5 5 5 Bug! 5 Side effect! var is the problem, because it is function scoped instead of block scoped
  4. for (var i = 0; i < 5; i ++)

    { setTimeout(() => console.log(i), 1) } console.log(i) 0 1 2 3 4 No bug ReferenceError: j is not defined No side effect let let is the solution, because it is block scoped
  5. (function () { console.log(dog) var dog = '' console.log(cat) let

    cat = '' }()) undefined ReferenceError: cat is not defined
  6. const user1 = { name: 'Melanie', icon: '' } const

    user2 = { name: 'Ktja', icon: '' } user2.name = 'Katja' user1 = { name: 'Basti', icon: '' } let user1 = { name: 'Basti', icon: '' } TypeError: Assignment to constant variable. Error at runtime SyntaxError: Identifier 'user1' has already been declared Error at compile time "Katja" No error
  7. Legend • const and let • Arrow functions • Extended

    parameter handling • Template literals • Enhanced object properties • Destructuring • Modules • Classes • Promises • Async Await • Proxy • Linear Data Flow • Generators • Online Ressources
  8. const amountMoneySaved = function (products) { return products .map(function (p)

    { return p.price }) .reduce(function (a, b) { return a + b }, 0) - products .filter(function (p) { return p.price !== p.originalPrice }) .map(function (p) { return p.originalPrice }) .reduce(function (a, b) { return a + b }, 0) } const amountMoneySaved = products => products .map(p => p.price) .reduce((a, b) => a + b, 0) - products .filter(p => p.price !== p.originalPrice) .map(p => p.originalPrice) .reduce((a, b) => a + b, 0) lines: 20 => 9 (45%) chars: 402 => 232 (58%) =>
  9. // expression body const boomerang = x => x //

    statement body const boomerang = x => { return x }
  10. Legend • const and let • Arrow functions • Extended

    parameter handling • Template literals • Enhanced object properties • Destructuring • Modules • Classes • Promises • Async Await • Proxy • Linear Data Flow • Generators • Online Ressources
  11. const totalWeightIsLowEnough = (allowedWeight, ...weights) => weights.reduce((a, b) => a

    + b) <= allowedWeight totalWeightIsLowEnough(900, 90, 100, 70) // true totalWeightIsLowEnough(800, 90, 100, 70, 120, 95, 90, 70, 80, 70, 50) // false Gather the rest of the given parameters into one array called weights
  12. const array1 = [3, 4] const array2 = [1, 2,

    ...array1, 5, 6] // [1, 2, 3, 4, 5, 6] const abc = 'abc' const chars = [ ...abc] // ['a', 'b', 'c'] Spread a given iterable into separate values. Opposite of the rest parameter.
  13. Legend • const and let • Arrow functions • Extended

    parameter handling • Template literals • Enhanced object properties • Destructuring • Modules • Classes • Promises • Async Await • Proxy • Linear Data Flow • Generators • Online Ressources
  14. const shippingAndShop = (shipping, img, shopName = '') => `<div

    class="s24_shipping_and_shop"> <div class="s24_shipping"> <img class="s24_shipping_img" src="${img}"> ${shipping} € </div> ${shopName ? `<div class="s24_shop">${shopName}</div>` : ''} </div>` Multiline strings and interpolation-inception
  15. const userInput = ' </div><script>evilCode() </script>' <h1>User input </h1><div> </div><script>evilCode()

    </script> </div> <h1>User input </h1><div>evilCode() </div> const html2text = (strings, ...values) => strings.map( (string, i) => string + (values[i] || '').replace(/(<([^>]+)>)/g, '') ).join('') const output = html2text `<h1>User input</h1><div>${userInput} </div>` const output = `<h1>User input</h1><div>${userInput} </div>`
  16. Legend • const and let • Arrow functions • Extended

    parameter handling • Template literals • Enhanced object properties • Destructuring • Modules • Classes • Promises • Async Await • Proxy • Linear Data Flow • Generators • Online Ressources
  17. const name = 'Kim' const age = 30 const person

    = { name, age } Property shorthand
  18. const name = 'Kim' const age = 30 const person

    = { name, age, say(str) { console.log(str) } } Method properties
  19. Legend • const and let • Arrow functions • Extended

    parameter handling • Template literals • Enhanced object properties • Destructuring • Modules • Classes • Promises • Async Await • Proxy • Linear Data Flow • Generators • Online Ressources
  20. Object Matching const { job, name } = { name:

    'Helge', age: 61, job: 'German comedian and jazz musician' } const helge = `${name} is a ${job}.`
  21. Parameter Context Matching const { left: x, top: y }

    = someDOMNode.getBoundingClientRect() `Coordinates of element: (${x},${y})`
  22. Legend • const and let • Arrow functions • Extended

    parameter handling • Template literals • Enhanced object properties • Destructuring • Modules • Classes • Promises • Async Await • Proxy • Linear Data Flow • Generators • Online Ressources
  23. // modules/cowsay.js const cowsay = whatYaSay => ` _${'_'.repeat(whatYaSay.length)}_ <

    ${whatYaSay} > _${'_'.repeat(whatYaSay.length)}_ \\ ^ __^ \\ (oo)\_______ ( __) \\ ) \\/\\ ||----w | || ||` export default cowsay // app.js import cowsay from './modules/cowsay' document.querySelector('.stable').innerHTML = cowsay('All the devs in the house say heeeeyo!')
  24. Legend • const and let • Arrow functions • Extended

    parameter handling • Template literals • Enhanced object properties • Destructuring • Modules • Classes • Promises • Async Await • Proxy • Linear Data Flow • Generators • Online Ressources
  25. class Vehicle { constructor(color) { this.color = color this.km =

    0 } drive(km) { this.km += km } } class Car extends Vehicle { constructor(color) { super(color) } honk() { console.log(`honk honk! I am ${this.color} and have driven ${this.km}km`) } } const myCar = new Car('orange') myCar.drive(500) myCar.honk()
  26. // Vehicle is the supertype function Vehicle(color) { this.color =

    color this.km = 0 } Vehicle.prototype.drive = function (km) { this.km += km } // Car is the subtype function Car(color) { // inheritance part 1: "Constructor stealing" Vehicle.call(this, color) } // inheritance part 2: "prototype chaining" Car.prototype = Object.create(Vehicle.prototype) // adding a method to the subtype Car.prototype.honk = function () { console.log(`honk honk! I am ${this.color} and have driven ${this.km}km`) } const myCar = new Car('green') myCar.drive(800) myCar.honk()
  27. Legend • const and let • Arrow functions • Extended

    parameter handling • Template literals • Enhanced object properties • Destructuring • Modules • Classes • Promises • Async Await • Proxy • Linear Data Flow • Generators • Online Ressources
  28. const sayHiAfterOneSecond = () => new Promise((resolve, reject) => {

    setTimeout(() => resolve('Hi!'), 1000) }) sayHiAfterOneSecond() .then(hi => { console.log(hi) }) .catch(e => { console.error(e) })
  29. Legend • const and let • Arrow functions • Extended

    parameter handling • Template literals • Enhanced object properties • Destructuring • Modules • Classes • Promises • Async Await • Proxy • Linear Data Flow • Generators • Online Ressources
  30. Legend • const and let • Arrow functions • Extended

    parameter handling • Template literals • Enhanced object properties • Destructuring • Modules • Classes • Promises • Async Await • Proxy • Linear Data Flow • Generators • Online Ressources
  31. const proxy = new Proxy(observeMe, { set(target, property, value, receiver)

    { moduleA.render(value) moduleB.render(value) moduleC.render(value) return true } })
  32. Legend • const and let • Arrow functions • Extended

    parameter handling • Template literals • Enhanced object properties • Destructuring • Modules • Classes • Promises • Async Await • Proxy • Linear Data Flow • Generators • Online Ressources
  33. const fireClickoutTrackingPixel = productNode => Box(document.createElement('img')) .map(pixel => Object.assign(pixel, {

    src: extractTrackingPixelSrc(productNode), onload: () => document.body.removeChild(pixel) })) .fold(pixel => document.body.appendChild(pixel)) const clickoutHandler = event => Either(findProductNodeByChildNode(event.target)) .map(openClickoutInNewTab) .fold( () => {}, fireClickoutTrackingPixel )
  34. Legend • const and let • Arrow functions • Extended

    parameter handling • Template literals • Enhanced object properties • Destructuring • Modules • Classes • Promises • Async Await • Proxy • Linear Data Flow • Generators • Online Ressources
  35. function* fibonacci() { let left = 0 let right =

    1 while (true) { const current = left left = right right = current + left yield current } } const sequence = fibonacci() sequence.next().value // 0 sequence.next().value // 1 sequence.next().value // 1 sequence.next().value // 2 sequence.next().value // 3 sequence.next().value // 5
  36. Legend • const and let • Arrow functions • Extended

    parameter handling • Template literals • Enhanced object properties • Destructuring • Modules • Classes • Promises • Async Await • Proxy • Linear Data Flow • Generators • Online Ressources