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

ECMAScript 2016+

ECMAScript 2016+

Avatar for Andrei Sierkov

Andrei Sierkov

March 01, 2017

More Decks by Andrei Sierkov

Other Decks in Programming

Transcript

  1. ECMAScript 2017 and beyond by Axel Rauschmayer • @rauschma •

    Books by Axel: ExploringJS.com • https://youtu.be/5Kw4XVSb4P4 • https://speakerdeck.com/ rauschma/ecmascript-2017- and-beyond
  2. ECMAScript vs JavaScript • ECMAScript is a standard hosted by

    Ecma International • JavaScript is a language based on ECMAScript • Also, ActionScript (Flash), JScript (Microsoft)
  3. TC39 Ordinary • Adobe • AMD • eBay • Google

    • HewlettPackard • Hitachi • IBM • Intel • KonicaMinolta • Yahoo Associate • Apple • Canon • Facebook • Fujitsu • JREastMechatronics • Netflix • NipponSignal • NXP • OMRONSocialSolutions • Ricoh • Sony • Toshiba • Twitter https://github.com/orgs/tc39/people
  4. ECMAScript versions • ECMAScript 1 (June 1997) • first version

    • ECMAScript 2 (June 1998) • editorial changes to align with ISO
  5. ECMAScript versions • ECMAScript 3 (December 1999): many core features

    • regular expressions • better string handling • try/catch exception handling • tighter definition of errors • formatting for numeric output • some other enhancements
  6. ECMAScript versions • ECMAScript 4 • classes, • a module

    system, • optional type annotations and static typing, probably using a structural type system, • generators and iterators, • destructuring assignment • algebraic data types. • … • abandoned in July 2008!
  7. ECMAScript versions • ECMAScript 5 (December 2009): • strict mode

    • clarifications for 3rd edition specs • getters, setters • JSON • Array prototype methods and some Object methods
  8. ECMAScript versions • ECMAScript 6 or ECMAScript 2015 (June 2015)

    • arrow functions • classes • enhanced object literals • template strings • destructuring • default and rest func arguments, spread for arrays • let + const • iterators + for…of • generators • modules • … many more https://github.com/lukehoban/es6features
  9. New TC39 process • Each feature is managed individually •

    Each feature has it’s own stages (0-4) • Once a year, new ECMAScript version with ready (at stage 4) features
  10. Stage 0: strawman • First sketch • Submitted by TC39

    member or TC39 contributor • Required • Review at TC39 meeting
  11. Stage 1: proposal • Actual proposal • Required • Identify

    champion(s), including one TC39 member • Spec: prose, example, API, semantics and algorythms • Some implementation: polyfills and demos • Changes are still expected
  12. Stage 2: draft • Some spec • Required: • at

    least two implementations (including one transpiler) • Only incremental changes are expected
  13. Stage 3: candidate • Mostly finished, now needs feedback from

    implementations • Required • Spec text is complete • Signed off by reviewers and editor • At least two spec-compliant implementations
  14. Stage 4: finished • Ready to be included in the

    ES spec • Required • Test262 acceptance tests (performance tests, more then 11000 as of 2013) • Practical experience • Editor must sign off on the spec text • Will be included in next version of standard
  15. ECMAScript 2016 • Released in June 2016 • Two new

    features • Array.prototype.includes • Exponentiation operator
  16. Array.prototype.includes ['a', 'b', 'c'].includes('a'); // true
 ['a', 'b', 'c'].includes('d'); //

    false
 
 [NaN].includes(NaN); // true
 [NaN].indexOf(NaN) >= 0; // false

  17. Exponentiation operator // x ** y is same as Math.pow(x,

    y)
 const squared = 3 ** 2; // 9
 let num = 3;
 num **= 2; // same: num = num ** 2
 console.log(num); // 9
  18. ECMAScript 2017 • Async Functions (Brian Terlson) • Shared memory

    and atomics (Lars T. Hansen) • Object.values/Object.entries (Jordan Harband) • String padding (Jordan Harband, Rick Waldron) • Object.getOwnPropertyDescriptors() (Jordan Harband, Andrea • Giammarchi) • Trailing commas in function parameter lists and calls (Jeff Morrison)
  19. Async Functions function fetchJsonViaPromises(url) {
 return fetch(url) // browser API,

    returns Promise
 .then(request => request.text()) // returns Promise
 .then(text => {
 return JSON.parse(text);
 })
 .catch(error => {
 console.log(`ERROR: ${error.stack}`);
 });
 } 
 async function fetchJsonAsync(url) {
 try {
 const request = await fetch(url);
 const text = await request.text();
 return JSON.parse(text);
 }
 catch (error) {
 console.log(`ERROR: ${error.stack}`);
 }
 }
  20. Async Functions // Async function declaration
 async function foo() {}

    
 // Async function expression
 const foo = async function () {}; 
 // Async arrow function
 const foo = async () => {}; 
 // Async method definition (in classes, too)
 const obj = { async foo() {} };
  21. Async Function as a promise async function asyncIsOne(a) {
 if

    (a === 1) {
 return 'yes'
 } else {
 throw new Error('Problem!');
 }
 } 
 asyncIsOne(1)
 .then(x => console.log(x)); 
 // yes
 
 asyncIsOne(2)
 .catch(err => console.log(err));
 // Error: Problem!
  22. Handling rejected Promises inside async functions async function asyncFunc() {


    try {
 await otherAsyncFunc();
 } catch (err) {
 console.error(err);
 }
 }
 
 
 // Equivalent to:
 function asyncFunc() {
 return otherAsyncFunc()
 .catch(err => {
 console.error(err);
 });
 }
  23. Shared Array Buffers • New – Shared Array Buffers: •

    A primitive building block for higher-level concurrency abstractions • Share data between workers • Let’s you compile threaded C++ code to JavaScript
  24. History of concurrency in JavaScript • Single main thread +

    asynchronicity via callbacks • Web Workers • Originally: copy and send strings • Structured cloning: copy and send structured data • Transferables: move and send structured data
  25. Creating and sending a Shared Array Buffer //----- main.js -----


    const worker = new Worker(‘worker.js'); 
 // To be shared
 const sharedBuffer = new SharedArrayBuffer(
 10 * Int32Array.BYTES_PER_ELEMENT); 
 // Share sharedBuffer with the worker
 worker.postMessage({sharedBuffer}); // clone 
 // Local only
 const sharedArray = new Int32Array(sharedBuffer);
  26. Problems // May be rearranged by compiler // Source code


    while (sharedArray[0] === 1) ; 
 // turns into let tmp = sharedArray[0];
 while (tmp === 1) ; // runs never or forever
 
 // Writes may be reorderer // main.js
 sharedArray[1] = 11;
 sharedArray[2] = 22; 
 // worker.js
 while (sharedArray[2] !== 22) ;
 console.log(sharedArray[1]); // 0 or 11
  27. Atomics • Operations are non-interruptible (atomic) – think transactions in

    DBs • Order of writes and reads is fixed • No reads or writes get eliminated
  28. Atomics Usage // main.js
 Atomics.store(sharedArray, 0, 2);
 // worker.js
 while

    (Atomics.load(sharedArray, 0) === 0) ;
 console.log(Atomics.load(sharedArray, 0)); // 2
  29. Atomics Usage Loading and storing: • Atomics.load(ta : TypedArray<T>, index)

    : T • Atomics.store(ta : TypedArray<T>, index, value : T) : T • Atomics.exchange(ta : TypedArray<T>, index, value : T) : T • Atomics.compareExchange(ta : TypedArray<T>, index, expectedValue, replacementValue) : T Waiting and waking: • Atomics.wait(ta: Int32Array, index, value, timeout=Number.POSITIVE_INFINITY) : ('not-equal' | 'ok' | ‘timed-out') • Atomics.wake(ta : Int32Array, index, count)
  30. Atomics Usage Simple modifications of Typed Array elements: • Atomics.add(ta

    : TypedArray<T>, index, value) : T • Atomics.sub(ta : TypedArray<T>, index, value) : T • Atomics.and(ta : TypedArray<T>, index, value) : T • Atomics.or(ta : TypedArray<T>, index, value) : T • Atomics.xor(ta : TypedArray<T>, index, value) : T
  31. Object.entries() • Object.entries() returns an Array of [key,value] pairs: Object.entries({

    one: 1, two: 2 });
 // [ [ 'one', 1 ], [ 'two', 2 ] ]
 
 const obj = { one: 1, two: 2 };
 for (const [k, v] of Object.entries(obj)) {
 console.log(k, v);
 }
 // "one" 1
 // "two" 2
  32. String padding '1'.padStart(3, '0');
 // '001'
 'x'.padStart(3);
 // ' x'


    
 '1'.padEnd(3, '0');
 // '100'
 'x'.padEnd(3);
 // 'x '
  33. Object. getOwnPropertyDescriptors() const obj = {
 [Symbol('foo')]: 123,
 get bar()

    { return 'abc' },
 };
 console.log(Object.getOwnPropertyDescriptors(obj));
 // Output:
 // {
 // [Symbol('foo')]:
 // { value: 123,
 // writable: true,
 // enumerable: true,
 // configurable: true },
 // bar:
 // { get: [Function: bar],
 // set: undefined,
 // enumerable: true,
 // configurable: true } }
  34. Trailing commas in function parameter lists and calls const obj

    = {
 first: 'Jane',
 last: 'Doe',
 };
 const arr = [
 'red',
 'green',
 'blue',
 ]; 
 console.log(arr.length); // 3
  35. After ES2017 • Stage 3 • import() (Domenic Denicola) •

    Asynchronous Iteration (Domenic Denicola) • Rest/Spread Properties (Sebastian Markbage) • Lifting Template Literal Restriction (Tim Disney) • Function.prototype.toString revision (Michael Ficarra)
  36. import() • Load modules dynamically: import('./dir/someModule.js')
 .then(someModule => someModule.foo()); •

    Code splitting: load parts of your program on demand. • Conditional loading of modules: if (cond) { import(···).then(···) } • Computed module specifiers: import('module'+count).then(···)
  37. Rest and spread operators for properties const obj = {foo:

    1, bar: 2, baz: 3};
 const {foo, ...rest} = obj;
 // Same as:
 // const foo = 1;
 // const rest = {bar: 2, baz: 3};
 function f({param1, param2, ...rest}) { // rest
 console.log('All parameters: ',
 {param1, param2, ...rest}); // spread
 return param1 + param2;
 }
 
 > const obj = {foo: 1, bar: 2};
 > {...obj, baz: 3}
 { foo: 1, bar: 2, baz: 3 }
  38. Asynchronous iteration // Asynchronous iteration:
 for await (const l of

    readLinesAsync(fileName)) {
 console.log(l);
 }
 
 async function f() {
 const aI = createAsyncIterable(['a', 'b']);
 for await (const x of aI) {
 console.log(x);
 }
 }
 // Output:
 // a
 // b • Works inside: • Async functions • Async generators (new)
  39. Asynchronous generators: yield and await async function* createAsyncIterable(syncIterable) {
 for

    (const elem of syncIterable) {
 yield elem;
 }
 }
 
 async function* id(asyncIterable) {
 for await (const elem of asyncIterable) {
 yield elem;
 }
 }
  40. Function.prototype. toString revision • Improved spec of toString() for functions:

    • Return source code whenever possible • Previously: optional • Otherwise: standardised placeholder • Previously: must cause SyntaxError (no guarantee)
  41. And later • global object • SIMD: single instruction, multiple

    data const a = SIMD.Float32x4(1.0, 2.0, 3.0, 4.0);
 const b = SIMD.Float32x4(5.0, 6.0, 7.0, 8.0);
 const c = SIMD.Float32x4.add(a,b); • Big integers const x = BigInt.asUintN(64, 1234n);
 const y = BigInt.asUintN(64, 5678n);
 const result = BigInt.asUintN(64, x*y);