Slide 1

Slide 1 text

Javascript ++ Friedel Ziegelmayer 29. April 2015

Slide 2

Slide 2 text

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

Slide 3

Slide 3 text

DIFFERENT KIND OF FEATURES • Fixing Mistakes • Syntactic Sugar • All New • Better Standard Library • Bonus: ES7 & Beyond

Slide 4

Slide 4 text

Fixing Mistakes

Slide 5

Slide 5 text

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) }

Slide 6

Slide 6 text

Syntactic Sugar

Slide 7

Slide 7 text

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()

Slide 8

Slide 8 text

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 ]

Slide 9

Slide 9 text

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]) })

Slide 10

Slide 10 text

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'] = []

Slide 11

Slide 11 text

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 }

Slide 12

Slide 12 text

Default Values function hello(a, b = 'Mr.') { log(a + ' ' + b) } hello('hi') hello('hi', ‘Friedel') // hi Mr. // hi Friedel

Slide 13

Slide 13 text

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]

Slide 14

Slide 14 text

Spread Operator const myList = [1, 2, 3, 4] const empty = [1] empty.push(...myList) log(empty) // [1, 1, 2, 3, 4]

Slide 15

Slide 15 text

Template Literals log(`1 + 1 = ${1 + 1}`) // 1 + 1 = 2 log(`This is a multiline string ----- with some fancy format.`)

Slide 16

Slide 16 text

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}). `)

Slide 17

Slide 17 text

Binary and Octal Literals const myBinary = 0b110101 const myOctal = 0o767

Slide 18

Slide 18 text

All New

Slide 19

Slide 19 text

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.

Slide 20

Slide 20 text

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

Slide 21

Slide 21 text

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’

Slide 22

Slide 22 text

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 ]

Slide 23

Slide 23 text

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.

Slide 24

Slide 24 text

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

Slide 25

Slide 25 text

Better Libraries

Slide 26

Slide 26 text

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)]) })

Slide 27

Slide 27 text

Object.assign Object.assign({}, { hey: 1 }, { you: 2 }, { hey: 3 }) // {hey: 3, you: 2}

Slide 28

Slide 28 text

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

Slide 29

Slide 29 text

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

Slide 30

Slide 30 text

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

Slide 31

Slide 31 text

BEYOND ES6

Slide 32

Slide 32 text

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

Slide 33

Slide 33 text

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

Slide 34

Slide 34 text

Object Spread const toys = {car: 5000, doll: 100} log({pc: 2000, ...toys}) // { pc: 2000, car: 5000, doll: 100 }

Slide 35

Slide 35 text

Exponentiation Operator log(`10^2 is ${10**2}`) // 10^2 is 100

Slide 36

Slide 36 text

Resources • http://babeljs.io • https://kangax.github.io/compat-table/es6/ • esdiscuss.org • https://speakerdeck.com/rauschma/ecmascript-6-in-theory-and-practice • http://www.2ality.com/