KEMBAR78
What's New in JavaScript | PDF
WHAT’S NEW IN
JAVASCRIPT?
Sabre Labs • Lunch-n-Learn / Tech Talk • Aug 1, 2018
WHY DOES IT MATTER?
MORE DATA
Source: octoverse.github.com
“The State of the Octoverse 2017”
REALLY?
Yes, really.
NOT CONVINCED?
JavaScript (+ TypeScript) has it all…
• Imperative programming? Yes.
• Object-oriented programming? Yes.
• Functional programming? Yes.
• Procedural programming? Yes.
• Event-driven programming? Yes.
• Asynchronous programming? Yes.
• Reflection? Yes.
• Portability? Yes.
• Closures? Yes.
• Lambdas? Yes.
• Variable scoping? Yes.
• Strong and weak typing? Yes and yes.
• Garbage collection? Yes.
• Timers? Yes.
• Pattern matching? Yes.
• Destructuring? Yes.
• Cascading? Yes.
• Exception handling? Yes.
• Non-blocking I/O? Yes.
• JSON? Of course!
• Debug tools? Many.
• Good for front end dev? Yes.
• Good for back end dev? Yes.
VERSIONS
# Name Description
1 ECMAScript 1 (1997) First edition
2 ECMAScript 2 (1998) Editorial changes
3 ECMAScript 3 (1999) Added RegEx and try/catch
4 ECMAScript 4 Never released
5 ECMAScript 5 (2009) Added strict mode, JSON, and more
5.1 ECMAScript 5.1 (2011) Editorial changes
6 ECMAScript 2015 (ES6) Added obscene amount of new features
7 ECMAScript 2016 (ES7) Added exponential operator and Array.prototype.includes
8 ECMAScript 2017 (ES8) Added async/await, string padding, and more
9 ECMAScript 2018 (ES9) Added rest/spread operators, async iteration, and more
ECMASCRIPT 2015 (ES6)
Just the highlights / useful parts
TEMPLATE LITERALS
var message = `Hi, my name is ${first} ${last}.`;
console.log(`Received: ${JSON.stringify(obj)}`);
ARROW FUNCTIONS
${'.btn'}.click(event => {this.sendData();}); // jQuery example
var msgs = ids.map(value => `ID is ${value}`); // implicit return value
request('https://wordsapiv1.p.mashape.com/words/example',
(err, res, body) => {
if (err) { return console.error(err); }
console.log('statusCode:', res.statusCode);
console.log('body:', body);
}
);
BLOCK-SCOPED VARIABLES
if (some.value == some.other.value) {
let localCounter = 0;
const TAX = .0825;
:
:
}
SPREAD OPERATOR
function (...args) { }
var arr1 = [1, '2', 3];
var arr2 = [...arr1, '4', 5];
var sarahManning = {...kendallMalone}; // shallow obj cloning
// this one is only supported in ES9 and above!
var newObject = {...template, newAttr, oldAttr: newValue};
ITERATORS & GENERATORS
for (let n of numbers) { … }
function* range (start, end, step) {
while (start < end) {
yield start;
start += step;
}
}
for (let i of range(1, 20, 2)) { … }
function* ?
WTF!
INTERNATIONALIZATION
var coll = new Intl.Collator("de");
words.sort(coll.compare);
var nf = Intl.NumberFormat("en-US");
elem.value = nf.format(number);
var euro = Intl.NumberFormat("de-DE", {style:"currency", currency: "EUR"})
var response = `Your balance is ${euro.format(bal)`;
var dtf = Intl.DateTimeFormat("en-US", options);
console.log(dtf.format(new Date()) + " something happened”);
Also: Intl.PluralRules could be handy but has limited support at the moment.
OTHER FEATURES TO BE AWARE OF
• Classes
• Default function parameters
• Destructuring assignment and object property assignment
• Modules (export/import)
• Promises
• Proxying
• Reflection
• Sets, WeakSets, Maps, and WeakMaps
• Symbols
• Typed arrays
• Array methods find() and findIndex()
• String methods startsWith(), endsWith(), includes(), repeat()
ECMASCRIPT 2016 (ES7)
This is going to be really brief
EXPONENTIATION
var googol = 10 ** 100;
var euler = Math.E ** (Math.PI * i) + 1; // use your imagination
ARRAY INCLUDES
> ['red', 'yellow', 'green', 'blue'].includes['red’]
true
> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29].includes[1]
false
ECMASCRIPT 2017 (ES8)
I can’t await to tell you what I async of ES8
ARE CALLBACKS DRIVING YOU MAD?
example from
callbackhell.com
THERE’S A BETTER WAY
var promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('Done'), 2000);
});
async function suspense() {
console.log('Wait for it...’);
var result = await promise;
console.log(result);
}
suspense();
How is this
better?
THERE’S MORE!
• Promise.all(iterable)
• Aggregates the results of multiple Promises (e.g., array)
• Waits for all Promises to be fulfilled
• Fails fast if any Promise is rejected
NEW FEATURES FOR WEB WORKERS
• Web Worker?
• Background script (thread) for a web application
• Good for prefetching data, real-time text formatting, image/video analysis, background I/O,
processing large JSON responses, etc.
• Not to be confused with Service Workers
• Event-driven scripts that run independently of web pages
• Useful for browser push notifications and building progressive web apps
• SharedArrayBuffer
• Buffer that can be shared between web workers
• Nice, right? Nope… it’s currently disabled in all major browsers b/c of Spectre vulnerability
• Atomics
• Global variable that enables synchronization with other workers
• Now also useless L
ECMASCRIPT 2018 (ES9)
Released as ECMA-262 in June, 2018
ASYNCHRONOUS ITERATION
async function* createAsyncIterable(array) {
for (const elem of array) { yield elem; }
}
async function f() {
const asyncIterable = createAsyncIterable(['a', 'b']);
const asyncIterator = asyncIterable[Symbol.asyncIterator]();
console.log(await asyncIterator.next()); // { value: 'a', done: false }
console.log(await asyncIterator.next()); // { value: 'b', done: false }
console.log(await asyncIterator.next()); // { value: undefined, done: true }
}
ANOTHER EXAMPLE
REGEXP ENHANCEMENTS
• Named capture groups
/(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/.exec('2018-06-29').groups.year
• Unicode property escapes
Look this up… it’s complicated (but really cool)
• Lookbehind assertions
/(?<=$)[0-9]+/ // captures digits following a dollar sign ($)
• s (dotAll) flag
• /s means dot (.) also matches line terminator chars
• /u means dot (.) also matches unicode characters
OBJECT DESTRUCTURING WITH
REST OPERATOR
let { foo, ...remaining } = { foo: 1, bar: 2, baz: 3, qux: 4 };
console.log(foo); // 1
console.log(remaining); // {bar: 2, baz: 3, qux: 4}
let { ...shallowClone } = { x: 1, foo: () => {…} };
console.log(shallowClone); // {x: 1, foo: ƒ}
DEFINING OBJECT LITERALS WITH
SPREAD OPERATOR
We covered this earlier. More examples:
// clone enumerable own properties of obj
let clone1 = {...obj}
// clone object along with its prototype (class)
let clone2 = {__proto__: Object.getPrototypeOf(obj), ...obj}
// combine two objects
let merged = {...obj1, ...obj2}
FINALLY: FINALLY FOR PROMISES
var promise = new Promise((resolve, reject) => { … });
promise
.then(result => {...})
.catch(error => {...})
.finally(() => {...}) // always do this, even if there’s
// a ‘return’ in then() or catch()
// or exception is not caught
// or catch() (re-)throws exception

What's New in JavaScript

  • 1.
    WHAT’S NEW IN JAVASCRIPT? SabreLabs • Lunch-n-Learn / Tech Talk • Aug 1, 2018
  • 2.
    WHY DOES ITMATTER?
  • 3.
    MORE DATA Source: octoverse.github.com “TheState of the Octoverse 2017”
  • 4.
  • 5.
    NOT CONVINCED? JavaScript (+TypeScript) has it all… • Imperative programming? Yes. • Object-oriented programming? Yes. • Functional programming? Yes. • Procedural programming? Yes. • Event-driven programming? Yes. • Asynchronous programming? Yes. • Reflection? Yes. • Portability? Yes. • Closures? Yes. • Lambdas? Yes. • Variable scoping? Yes. • Strong and weak typing? Yes and yes. • Garbage collection? Yes. • Timers? Yes. • Pattern matching? Yes. • Destructuring? Yes. • Cascading? Yes. • Exception handling? Yes. • Non-blocking I/O? Yes. • JSON? Of course! • Debug tools? Many. • Good for front end dev? Yes. • Good for back end dev? Yes.
  • 7.
    VERSIONS # Name Description 1ECMAScript 1 (1997) First edition 2 ECMAScript 2 (1998) Editorial changes 3 ECMAScript 3 (1999) Added RegEx and try/catch 4 ECMAScript 4 Never released 5 ECMAScript 5 (2009) Added strict mode, JSON, and more 5.1 ECMAScript 5.1 (2011) Editorial changes 6 ECMAScript 2015 (ES6) Added obscene amount of new features 7 ECMAScript 2016 (ES7) Added exponential operator and Array.prototype.includes 8 ECMAScript 2017 (ES8) Added async/await, string padding, and more 9 ECMAScript 2018 (ES9) Added rest/spread operators, async iteration, and more
  • 8.
    ECMASCRIPT 2015 (ES6) Justthe highlights / useful parts
  • 9.
    TEMPLATE LITERALS var message= `Hi, my name is ${first} ${last}.`; console.log(`Received: ${JSON.stringify(obj)}`);
  • 10.
    ARROW FUNCTIONS ${'.btn'}.click(event =>{this.sendData();}); // jQuery example var msgs = ids.map(value => `ID is ${value}`); // implicit return value request('https://wordsapiv1.p.mashape.com/words/example', (err, res, body) => { if (err) { return console.error(err); } console.log('statusCode:', res.statusCode); console.log('body:', body); } );
  • 11.
    BLOCK-SCOPED VARIABLES if (some.value== some.other.value) { let localCounter = 0; const TAX = .0825; : : }
  • 12.
    SPREAD OPERATOR function (...args){ } var arr1 = [1, '2', 3]; var arr2 = [...arr1, '4', 5]; var sarahManning = {...kendallMalone}; // shallow obj cloning // this one is only supported in ES9 and above! var newObject = {...template, newAttr, oldAttr: newValue};
  • 13.
    ITERATORS & GENERATORS for(let n of numbers) { … } function* range (start, end, step) { while (start < end) { yield start; start += step; } } for (let i of range(1, 20, 2)) { … } function* ? WTF!
  • 14.
    INTERNATIONALIZATION var coll =new Intl.Collator("de"); words.sort(coll.compare); var nf = Intl.NumberFormat("en-US"); elem.value = nf.format(number); var euro = Intl.NumberFormat("de-DE", {style:"currency", currency: "EUR"}) var response = `Your balance is ${euro.format(bal)`; var dtf = Intl.DateTimeFormat("en-US", options); console.log(dtf.format(new Date()) + " something happened”); Also: Intl.PluralRules could be handy but has limited support at the moment.
  • 15.
    OTHER FEATURES TOBE AWARE OF • Classes • Default function parameters • Destructuring assignment and object property assignment • Modules (export/import) • Promises • Proxying • Reflection • Sets, WeakSets, Maps, and WeakMaps • Symbols • Typed arrays • Array methods find() and findIndex() • String methods startsWith(), endsWith(), includes(), repeat()
  • 16.
    ECMASCRIPT 2016 (ES7) Thisis going to be really brief
  • 17.
    EXPONENTIATION var googol =10 ** 100; var euler = Math.E ** (Math.PI * i) + 1; // use your imagination
  • 18.
    ARRAY INCLUDES > ['red','yellow', 'green', 'blue'].includes['red’] true > [2, 3, 5, 7, 11, 13, 17, 19, 23, 29].includes[1] false
  • 19.
    ECMASCRIPT 2017 (ES8) Ican’t await to tell you what I async of ES8
  • 20.
    ARE CALLBACKS DRIVINGYOU MAD? example from callbackhell.com
  • 21.
    THERE’S A BETTERWAY var promise = new Promise((resolve, reject) => { setTimeout(() => resolve('Done'), 2000); }); async function suspense() { console.log('Wait for it...’); var result = await promise; console.log(result); } suspense(); How is this better?
  • 22.
    THERE’S MORE! • Promise.all(iterable) •Aggregates the results of multiple Promises (e.g., array) • Waits for all Promises to be fulfilled • Fails fast if any Promise is rejected
  • 23.
    NEW FEATURES FORWEB WORKERS • Web Worker? • Background script (thread) for a web application • Good for prefetching data, real-time text formatting, image/video analysis, background I/O, processing large JSON responses, etc. • Not to be confused with Service Workers • Event-driven scripts that run independently of web pages • Useful for browser push notifications and building progressive web apps • SharedArrayBuffer • Buffer that can be shared between web workers • Nice, right? Nope… it’s currently disabled in all major browsers b/c of Spectre vulnerability • Atomics • Global variable that enables synchronization with other workers • Now also useless L
  • 24.
    ECMASCRIPT 2018 (ES9) Releasedas ECMA-262 in June, 2018
  • 25.
    ASYNCHRONOUS ITERATION async function*createAsyncIterable(array) { for (const elem of array) { yield elem; } } async function f() { const asyncIterable = createAsyncIterable(['a', 'b']); const asyncIterator = asyncIterable[Symbol.asyncIterator](); console.log(await asyncIterator.next()); // { value: 'a', done: false } console.log(await asyncIterator.next()); // { value: 'b', done: false } console.log(await asyncIterator.next()); // { value: undefined, done: true } }
  • 26.
  • 27.
    REGEXP ENHANCEMENTS • Namedcapture groups /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/.exec('2018-06-29').groups.year • Unicode property escapes Look this up… it’s complicated (but really cool) • Lookbehind assertions /(?<=$)[0-9]+/ // captures digits following a dollar sign ($) • s (dotAll) flag • /s means dot (.) also matches line terminator chars • /u means dot (.) also matches unicode characters
  • 28.
    OBJECT DESTRUCTURING WITH RESTOPERATOR let { foo, ...remaining } = { foo: 1, bar: 2, baz: 3, qux: 4 }; console.log(foo); // 1 console.log(remaining); // {bar: 2, baz: 3, qux: 4} let { ...shallowClone } = { x: 1, foo: () => {…} }; console.log(shallowClone); // {x: 1, foo: ƒ}
  • 29.
    DEFINING OBJECT LITERALSWITH SPREAD OPERATOR We covered this earlier. More examples: // clone enumerable own properties of obj let clone1 = {...obj} // clone object along with its prototype (class) let clone2 = {__proto__: Object.getPrototypeOf(obj), ...obj} // combine two objects let merged = {...obj1, ...obj2}
  • 30.
    FINALLY: FINALLY FORPROMISES var promise = new Promise((resolve, reject) => { … }); promise .then(result => {...}) .catch(error => {...}) .finally(() => {...}) // always do this, even if there’s // a ‘return’ in then() or catch() // or exception is not caught // or catch() (re-)throws exception