ecmascript 6 and beyond
TRANSCRIPT
Learn ES2015
let vs const
Template Literals
Arrow Functions
Default ParametersClasses
Spread Operator … Rest Operator …
Destructuring
Modules
for… of loop
Promises
Symbols
String Interpolation
Enhanced Object Literals
Maps
Sets
2
Arrow Functions// ES5 function expressions
const arr = [1, 2, 3];
const squares = arr.map(function (x)
{ return x * x });
// ES6 fat arrow => syntax
const arr = [1, 2, 3];
const squares = arr.map(x => x * x);
5
Arrow Function Syntax
() => { ... } // no parameter
x => { ... } // one parameter
(x, y) => { ... } // several parameters
x => { return x * x } // block
x => x * x // expression
6
var vs. let vs. const
function order(x, y) { if (x > y) { let tmp = x; x = y; y = tmp; } console.log(tmp===x); // ReferenceError: tmp is not defined
return [x, y];}
let works similarly to var, but the variable it declares is
block-scoped, it only exists within the current block. var
is function-scoped.
8
var vs. let vs. const
const foo;// SyntaxError: missing = in const declaration
const bar = 123;bar = 456; // TypeError: `bar` is read-only
const obj = {};obj.prop = 123;console.log(obj.prop); // 123
const works like let, but the variable you declare must be immediately
initialised, with a value that can’t be changed afterwards.
9
var vs. let vs. const
function logArgs(...args) { for (const [index, elem] of args.entries()) { const message = index + '. ' + elem; console.log(message); }}logArgs('Hello', 'everyone');
// Output:// 0. Hello// 1. everyone
10
var vs. let vs. constconst arr = [];for (var i=0; i < 3; i++) { arr.push(() => i);}arr.map(x => x()); // [3,3,3]
const arr = [];for (let i=0; i < 3; i++) { arr.push(() => i);}arr.map(x => x()); // [0,1,2]
11
Default Parameters
// OK: `y` accesses `x` after it has been declared
function foo(x=1, y=x) { return [x, y];}foo(); // [1,1]
// Exception: `x` tries to access `y` within TDZ
function bar(x=y, y=2) { return [x, y];}bar(); // ReferenceError
13
Object Destructuring
15
const obj = { first: 'Jane', last: 'Doe' };const {first: f, last: l} = obj; // f = 'Jane'; l = 'Doe'
// {prop} is short for {prop: prop}
const {first, last} = obj; // first = 'Jane'; last = 'Doe'
Array Destructuring
16
const iterable = ['a', 'b'];
const [x, y] = iterable; // x = 'a'; y = ‘b’
const [all, year, month, day] = /^(\d\d\d\d)-(\d\d)-(\d\d)$/ .exec(‘2999-12-31');
[a, b] = [b, a]; //swap values
Array Destructuring
17
const [,, x, y] = ['a', 'b', 'c', ‘d'];// x = 'c'; y = ‘d'
const [x, ...y] = ['a', 'b', 'c']; // x='a'; y=['b', ‘c']
const {length : len} = 'abc'; // len = 3
const {toString: s} = 123; // s = Number.prototype.toString
Rest operator …
18
const [x, ...y] = ['a', 'b', 'c']; // x='a'; y=['b', ‘c']
const [x, y, ...z] = ['a']; // x='a'; y=undefined; z=[]
const [x, ...[y, z]] = ['a', 'b', 'c'];// x = 'a'; y = 'b'; z = 'c'
Spread operator …
19
In function and constructor calls, the spread operator turns iterable values into arguments:
In Array literals, the spread operator turns iterable values into Array elements:
Math.max(-1, 5, 11, 3) // 11
Math.max(...[-1, 5, 11, 3]) // 11
Math.max(-1, ...[-1, 5, 11], 3) // 11
[1, ...[2,3], 4] // [1, 2, 3, 4]
Template Literals
20
String literals that can stretch across multiple lines and include interpolated expressions
Template Literals
21
const firstName = 'Jane';console.log(`Hello ${firstName}!How are youtoday?`);
// Output:// Hello Jane!// How are you// today?
Tagged template literals
22
tagFunction`Hello ${firstName} ${lastName}!`
tagFunction(['Hello ', ' ', '!'], firstName, lastName)
const str = String.raw`This is a textwith multiple lines.Escapes are not interpreted,\n is not a newline.`;
Classes
23
class Point { constructor(x, y) { this.x = x; this.y = y; } toString() { return `(${this.x}, ${this.y})`; }}
class ColorPoint extends Point { constructor(x, y, color) { super(x, y); this.color = color; } toString() { return super.toString() + ' in ' + this.color; }}
Multiple named exports
25
//------ lib.js ------
export const sqrt = Math.sqrt;export function square(x) { return x * x;}export function diag(x, y) { return sqrt(square(x) + square(y));}
//------ main.js ------
import { square, diag } from 'lib';console.log(square(11)); // 121console.log(diag(4, 3)); // 5
Single default exports
26
//------ myFunc.js ------
export default function () { ··· }
//------ main1.js ------
import myFunc from 'myFunc';myFunc();
//------ MyClass.js ------
export default class { ··· }
//------ main2.js ------
import MyClass from 'MyClass';const inst = new MyClass();
Use case 1: unique property keys
28
const MY_KEY = Symbol();const obj = {};
obj[MY_KEY] = 123;console.log(obj[MY_KEY]); // 123
Use case 2: constants representing concepts
29
const COLOR_RED = Symbol('Red');const COLOR_ORANGE = Symbol('Orange');const COLOR_YELLOW = Symbol('Yellow');
function getComplement(color) { switch (color) { case COLOR_RED: return COLOR_GREEN; case COLOR_ORANGE: return COLOR_BLUE; case COLOR_YELLOW: return COLOR_YELLOW; default: throw new Exception('Unknown color: '+color); }}