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

JavaScript++

 JavaScript++

Talk about features in ES6 and beyond.

Friedel Ziegelmayer

April 29, 2015
Tweet

Other Decks in Programming

Transcript

  1. WHAT’S IN A NAME • TC39: Ecma Technical Comittee 39

    • ECMAScript • ES5: ECMAScript Language Specification 5) • ECMAScript Harmony: Everything after ES5 • ES6/ES2015: ECMA-262 6th Edition - ECMAScript 2015 • JavaScript: Implementation of ECMAScript
  2. DIFFERENT KIND OF FEATURES • Fixing Mistakes • Syntactic Sugar

    • All New • Better Standard Library • Bonus: ES7 & Beyond
  3. Block Scope { let x = 'original' { const x

    = 'i shadow you' console.log(x) } x = 'redeclare' console.log(x) } // all good, outside of the block let x = 'something' console.log(x) }
  4. Classes class Toy { constructor(name) { this.name = name }

    hello() { log(this.name) } static defaultToy() { return new Toy('default') } } class SpecialToy extends Toy { constructor(name, value) { super(name) this.value = value } hello() { super.hello() log('My value is %s', this.value) } } const toy = new Toy('Car') toy.hello() const defaultToy = Toy.defaultToy() defaultToy.hello() const sToy = new SpecialToy('PC', 2000) sToy.hello()
  5. Modules // index.js import {sum, PI} from './math' import *

    as math from './math' import secrets from './secrets' console.log(sum(PI, 4)) console.log(math.PI) console.log(secrets) // 7.141 // 3.141 // [‘hello’, 123] // math.js export function sum(x, y) { return x + y } export var PI = 3.141 // secrets.js export default const [ 'hello', 123 ]
  6. Arrow Functions import {readFile} from 'fs' class Simple { read(file,

    done) { readFile(file, (err, res) => { // this still refers to the instance of Simple this.res = res.toString() done() }) } } const simple = new Simple() simple.read('es6.md', () => { log(simple.res.split('\n')[0]) })
  7. Destructering // List Matching const toys = ['car', 'pc', 'laptop',

    'doll'] const [first, , third] = toys // Object Matching const toyDescriptions = { car: {value: 100}, pc: {value: 2000}, laptop: {value: 600}, doll: {value: 40} } const {pc: {value}} = toyDescriptions // Object Matching in function parameters function logValue(name, {value}) { log('The value of the %s is $%s.', name, value) } logValue('laptop', toyDescriptions.laptop) // Fail-soft destructering with defaults const [a = 'toy'] = []
  8. Enhanced Object Literals const myProp = 'prop' const secret =

    '123' const obj = { // computed property values [myProp + '1']: 1, [myProp + '2']: 2, // Methods hello() { log('hello') }, // Super calls toString() { return 'fancy' + super.toString() }, // Shorthand secret }
  9. Default Values function hello(a, b = 'Mr.') { log(a +

    ' ' + b) } hello('hi') hello('hi', ‘Friedel') // hi Mr. // hi Friedel
  10. Rest Parameters function append(head, ...tail) { tail.forEach(function(elem) { head.push(elem) })

    return head } log(append([], 1, 2, 3, 4, 5)) // [1, 2, 3, 4, 5]
  11. Spread Operator const myList = [1, 2, 3, 4] const

    empty = [1] empty.push(...myList) log(empty) // [1, 1, 2, 3, 4]
  12. Template Literals log(`1 + 1 = ${1 + 1}`) //

    1 + 1 = 2 log(`This is a multiline string ----- with some fancy format.`)
  13. Tagged Templates function TAG(strings, ...values) { const clean = strings.map(s

    => { return s.replace(/(\r\n|\n|\r)\s*/gm, ' ').trim() }) let res = '' clean.forEach((val, i) => { res += val + (values[i] || '') }) return res } log(TAG` A more interesting way of removing line breaks (${1 + 1}). `)
  14. Map|Set // Set const s = new Set() s.add('first').add('second').add('first') log(s.size)

    // 2 log(s.has(‘second')) // true log(Array.from(s)) // [‘first’, ‘second’] // Map const m = new Map() m.set('first', 42) m.set(s, s.size) log(Array.from(m)) // [[‘first’, 42], [{}, 2]] log('The size of s is %s.', m.get(s)) // The size of s is 2.
  15. WeakMap|WeakSet // Weak Set const ws = new WeakSet() ws.add({data:

    42}) log('Size of the weak set: %s', ws.size) // Size of the weak set: undefined // Weak Map const wm = new WeakMap() wm.set(s, {secret: '123'}) log('Size of the weak map: %s', wm.size) // Size of the weak map: undefined
  16. Symbols const Hideout = (function () { const secret =

    Symbol('123') function Hideout(data) { this[secret] = data } Hideout.prototype.showSecret = function () { log(this[secret]) } return Hideout })() const hideout = new Hideout('my dark secret') log(hideout[‘123']) // undefined hideout.showSecret() // ‘my dark secret’
  17. Iterators let fibonacci = { [Symbol.iterator]() { let pre =

    0, cur = 1 return { next() { [pre, cur] = [cur, pre + cur] return {done: false, value: cur} } } } } let res = [] for (let n of fibonacci) { if (n > 1000) break res.push(n) } log(res) // [ 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987 ]
  18. Generators function* objectEntries(obj) { for (let key of Object.keys(obj)) {

    yield [key, obj[key]] } } const toys = {car: 100, pc: 2000, laptop: 500} const it = objectEntries(toys) log(it.next()) // { value: [ 'car', 100 ], done: false } log(it.next()) // { value: [ 'pc', 2000 ], done: false } log(it.next()) // { value: [ 'laptop', 500 ], done: false } log(it.next()) // { value: undefined, done: true } for (let [key, value] of objectEntries(toys)) { log('The value of %s is $%s.', key, value) } // The value of car is $100. // The value of pc is $2000. // The value of laptop is $500.
  19. Tail Call Optimisations function factorial(n, acc = 1) { if

    (n <= 1) return acc return factorial(n - 1, n * acc) } // Stack overflow in most implementations // today, but safe on arbitrary inputs in eS6 log(factorial(100000))
  20. Promises function timeout(duration = 0) { return new Promise((resolve, reject)

    => { setTimeout(resolve, duration) }) } timeout(1000) .then(() => { return timeout(2000) }) .then(() => { throw new Error("hmm") }) .catch(err => { return Promise.all([timeout(100), timeout(200)]) })
  21. New String Methods log('-'.repeat(12)) log('Does "hello world" include "wo"? %s',

    'hello world'.includes('wo')) log(‘-'.repeat(12)) // ------------ // Does "hello world" include "wo"? true // ------------
  22. New Array Methods const toys = ['doll', 'car', 'laptop'] log('The

    index of car is: %s.', toys.findIndex( x => x === 'car')) log([1, 2, 3, 4].fill(7, 2)) log('values', Array.from(toys.values())) log('keys', Array.from(toys.keys())) log('entries', Array.from(toys.entries())) } // The index of car is: 1. // [ 1, 2, 7, 7 ] // values [ 'doll', 'car', 'laptop' ] // keys [ 0, 1, 2 ] // entries [ [ 0, 'doll' ], [ 1, 'car' ], [ 2, 'laptop' ] ]
  23. New Math Methods log('Epsilon %s', Number.EPSILON) log('Is infinity an integer?

    %s', Number.isInteger(Infinity)) log('Is "NaN" a NaN?', Number.isNaN('NaN')) log('Hyperbolic arccosine of 3: %s', Math.acosh(3)) // Epsilon 2.220446049250313e-16 // Is infinity an integer? false // Is "NaN" a NaN? false // Hyperbolic arccosine of 3: 1.7627471740390859
  24. Class Properties class Cool { color = 'red' constructor(color) {

    if (color) { this.color = color } } boundColor = () => this.color unboundColor() { return this.color } } const cool = new Cool() log(cool.color) // red log(cool.boundColor.call({color: ‘green'})) // red log(cool.unboundColor.call({color: ‘green’})) // green
  25. Class Decorators function isTestable(value) { return function decorator(target) { target.prototype.isTestable

    = value } } @isTestable(true) class TestClass {} const cls = new TestClass() log('Is my class testable? %s.', cls.isTestable) // true
  26. Object Spread const toys = {car: 5000, doll: 100} log({pc:

    2000, ...toys}) // { pc: 2000, car: 5000, doll: 100 }