ES6 and Beyond
Cheat Sheet
Constants let vs var
> const EULER = 2.7182818284 > var average = 5
> EULER = 13 > var average = (average + 1) / 2
> EULER > average
> 2.7182818284 > 3
> let value = ‘hello world’
> let value = ‘what is new’
Warning! If array or object, the reference is kept // -> throws TypeError: Identifier 'value' has
constant. If the constant is a reference to an object, already been declared
you can still modify the content, but never change the
variable.
Be aware of Temporal Dead Zones:
> const CONSTANTS = []
> console.log(val) // -> 'undefined'
> CONSTANTS.push(EULER)
> var val = 3
> CONSTANTS
> console.log(val) // -> 3
> [ 2.7182818284 ]
> CONSTANTS = { ‘euler’: 2.7182818284 }
Because it's equivalent to:
> CONSTANTS
> [ 2.7182818284 ]
> var val
> console.log(val)
Binary, Octal and Hex Notation
> val = 3
> console.log(val)
> 0b1001011101 // 605
> 0o6745 // 3557
Variables declared with "let/const" do not get hoisted:
> 0x2f50a // 193802
> console.log(val)
New Types // -> Throws ReferenceError
> let val = 3
Symbols, Maps, WeakMaps and Sets > console.log(val) // -> 3
New Scoped Functions
Arrow Function
> {
… let cue = 'Luke, I am your father'
> setTimeout(() => {
… console.log(cue)
… console.log(‘delayed’)
… }
… }, 1000)
> 'Luke, I am your father'
Equivalent with Immediately Invoked
Equivalent with Anonymous Function Function Expressions (IIFE)
> (function () {
> setTimeout(function () { … var cue = 'Luke, I am your father'
… console.log(‘delayed’) … console.log(cue) // 'Luke, I am –
… }.bind(this), 1000) … }())
> console.log(cue) // Reference Error
Object Notation Novelties String Interpolation, Thanks to Template Literals
// Computed properties
> let key = new Date().getTime()
> const name = 'Tiger'
> let obj = { [key]: “value” }
> const age = 13
> obj
> console.log(`My cat is named ${name} and is
> { '1459958882881': 'value' }
${age} years old.`)
> My cat is named Tiger and is 13 years old.
// We can preserve newlines…
// Object literals
let text = ( `cat
balloon = { color, size };
dog
nickelodeon`
// Same as
)
balloon = {
color: color,
size: size
} Default Params
// Better method notations
obj = { > function howAreYou (answer = ‘ok’) {
foo (a, b) { … }, console.log(answer) // probably ‘ok’
bar (x, y) { … } }
}
Promises Classes, Inheritance, Setters, Getters
class Rectangle extends Shape {
constructor (id, x, y, w, h) {
super(id, x, y)
new Promise((resolve, reject) => {
this.width = w
request.get(url, (error, response,
this.height = h
body) => {
}
if (body) {
// Getter and setter
resolve(JSON.parse(body));
set width (w) { this._width = w }
} else {
get width () { return this._width }
resolve({});
}
}
})
class Circle extends Shape {
}).then(() => { ... })
constructor (id, x, y, radius) {
.catch((err) => throw err)
super(id, x, y)
this.radius = radius
// Parallelize tasks
}
Promise.all([
do_a(x) {
promise1, promise2, promise3
let a = 12;
]).then(() => {
super.do_a(x + a);
// all tasks are finished
}
})
static do_b() { ... }
}
Circle.do_b()
Destructuring Arrays Destructuring Objects
> let [a, b, c, d] = [1, 2, 3, 4]; > let luke = { occupation: 'jedi',
> console.log(a); father: 'anakin' }
> 1 > let {occupation, father} = luke
> b > console.log(occupation, father)
> 2 > jedi anakin
Spread Operator
...Go Destructuring Like a Boss
// Turn arrays into comma separated
// values and more
> function logger (...args) {
> const [ cat, dog, ...fish ] = [
console.log(‘%s arguments’,
‘schroedinger’, ‘Laika’, ‘Nemo’, ‘Dori’]
args.length)
> fish // -> [‘Nemo’, ‘Dori’]
args.forEach(console.log)
// arg[0], arg[1], arg[2]
}
...And Destructuring in the Future ES7
Or Do a Better Push
> let arr = [1, 2, 3]
> [...arr, 4, 5, 6] {a, b, ...rest} = { a:1, b:2, c:3, d:4 }
> [1, 2, 3, 4, 5, 6]
Async ES7 Await ES7
async function schrodinger () {
return new Promise((resolve, reject)
=> { try {
const result = Math.random > 0.5 console.log(await schrodinger())
setTimeout(() => { // -> ‘alive’
return result ? resolve(‘alive’) } catch (err) {
: reject(‘dead’) console.log(err)
}) // -> ‘dead’
}) }
}
Export ES7 Importing ES7
export function sumTwo (a, b) { import React from ‘react’
return a + b; import { EULER } from ‘./myexports’
} import * as stuff from ‘./myexports’
export const EULER = 2.7182818284 // equivalent to
let stuff = { sumTwo, EULER } import stuff from ‘./myexports’
export { stuff as default } // { sumTwo, EULER }
Generators
They return a objects that implement an iteration protocol. i.e. it has a next() method that returns { value: < some
value>, done: <true or false> }.
function* incRand (max) { // Asterisk defines this as a generator
while (true) {
// Pause execution after the yield, resume
// when next(<something>) is called
// and assign <something> to x
let x = yield Math.floor(Math.random() * max + 1);
max += x;
}
}
> var rng = incRand(2) // Returns a generator object
> rng.next() // { value: <between 1 and 2>, done: false }
> rng.next(3) // as above, but between 1 and 5
> rng.next() // NaN since 5 + undefined results in NaN
> rng.next(20) // No one expected NaN again?
> rng.throw(new Error('Unrecoverable generator state.'))
// Will be thrown from yield
ES6 Cheatsheet
Arrow function Default parameters
const sum = (a, b) => a + b function print(a = 5) {
console.log(a)
console.log(sum(2, 6)) // prints 8 }
print() // prints 5
print(22) // prints 22
let scope const
let a = 3 // can be assigned only once:
const a = 55
if (true) {
let a = 5 a = 44 // throws an error
console.log(a) // prints 5
}
console.log(a) // prints 3
Multiline string Template strings
console.log(` const name = 'Leon'
This is a const message = `Hello ${name}`
multiline string
`) console.log(message) // prints "Hello Leon"
String includes() String startsWith()
console.log('apple'.includes('pl')) // prints true console.log('apple'.startsWith('ap')) // prints true
console.log('apple'.includes('tt')) // prints false console.log('apple'.startsWith('bb')) // prints
false
String repeat() Destructuring array
console.log('ab'.repeat(3)) // prints "ababab" let [a, b] = [3, 7];
console.log(a); // 3
console.log(b); // 7
Destructuring object object property assignement
let obj = { const a = 2
a: 55, const b = 5
b: 44
}; const obj = { a, b }
let { a, b } = obj; // Before es6:
// obj = { a: a, b: b }
console.log(a); // 55
console.log(b); // 44 console.log(obj) // prints { a: 2, b: 5 }
object function assignement spread operator
const obj = { const a = [ 1, 2 ]
a: 5, const b = [ 3, 4 ]
b() {
console.log('b') const c = [ ...a, ...b ]
}
} console.log(c) // [1, 2, 3, 4]
obj.b() // prints "b"
Object.assign() Object.entries()
const obj1 = { a: 1 } const obj = {
const obj2 = { b: 2 } firstName: 'Vipul',
lastName: 'Rawat',
const obj3 = Object.assign({}, obj1, obj2) age: 22,
country: 'India',
console.log(obj3) // { a: 1, b: 2 } };
const entries = Object.entries(obj);
/* returns an array of [key, value]
pairs of the object passed
*/
console.log(entries);
/* prints
[
['firstName', 'Vipul'],
['lastName', 'Rawat'],
['age', 22],
['country', 'India']
];
*/
spread operator Destructuring Nested Objects
const a = { const Person = {
firstName: "Barry", name: "John Snow",
lastName: "Manilow", age: 29,
} sex: "male",
materialStatus: "single",
const b = { address: {
...a, country: "Westeros",
lastName: "White", state: "The Crownlands",
canSing: true, city: "Kings Landing",
} pinCode: "500014",
},
console.log(a) // {firstName: "Barry", lastName: };
"Manilow"}
const { address : { state, pinCode }, name } =
console.log(b) // {firstName: "Barry", lastName: Person;
"White", canSing: true}
console.log(name, state, pinCode) // John Snow
// great for modifying objects without side The Crownlands 500014
effects/affecting the original console.log(city) // ReferenceError
Copyright © 2018
www.developer-cheatsheets.com