Posts

ES2015+ cheatsheet

ES2015+ cheatsheet is A quick overview of new JavaScript features in ES2015, ES2016, ES2017, ES2018 and beyond.

Block scoping

Let

function fn () {
  let x = 0
  if (true) {
    let x = 1 // only inside this `if`
  }
}
 
 

Const

<span class="token keyword">const</span> a <span class="token operator">=</span> <span class="token number">1</span>

let is the new var. Constants work just like let, but can’t be reassigned. See: Let and const

Backtick strings

Interpolation

<span class="token keyword">const</span> message <span class="token operator">=</span> <span class="token template-string"><span class="token string">`Hello </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>name<span class="token interpolation-punctuation punctuation">}</span></span><span class="token string">`</span></span>

Multiline strings

<span class="token keyword">const</span> str <span class="token operator">=</span> <span class="token template-string"><span class="token string">`
hello
world
`</span></span>

Templates and multiline strings. See: Template strings

Binary and octal literals

<span class="token keyword">let</span> bin <span class="token operator">=</span> <span class="token number">0b1010010</span>
<span class="token keyword">let</span> oct <span class="token operator">=</span> <span class="token number">0o755</span>

See: Binary and octal literals

New methods

New string methods

<span class="token string">"hello"</span><span class="token punctuation">.</span><span class="token function">repeat</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span>
<span class="token string">"hello"</span><span class="token punctuation">.</span><span class="token function">includes</span><span class="token punctuation">(</span><span class="token string">"ll"</span><span class="token punctuation">)</span>
<span class="token string">"hello"</span><span class="token punctuation">.</span><span class="token function">startsWith</span><span class="token punctuation">(</span><span class="token string">"he"</span><span class="token punctuation">)</span>
<span class="token string">"hello"</span><span class="token punctuation">.</span><span class="token function">padStart</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// "   hello"</span>
<span class="token string">"hello"</span><span class="token punctuation">.</span><span class="token function">padEnd</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// "hello   " </span>
<span class="token string">"hello"</span><span class="token punctuation">.</span><span class="token function">padEnd</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">,</span> <span class="token string">'!'</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// hello!!!</span>
<span class="token string">"\u1E9B\u0323"</span><span class="token punctuation">.</span><span class="token function">normalize</span><span class="token punctuation">(</span><span class="token string">"NFC"</span><span class="token punctuation">)</span>

See: New methods

Classes

<span class="token keyword">class</span> <span class="token class-name">Circle</span> <span class="token keyword">extends</span> <span class="token class-name">Shape</span> <span class="token punctuation">{</span>

Constructor

  constructor (radius) {
    this.radius = radius
  }
 

Methods

  getArea () {
    return Math.PI * 2 * this.radius
  }
 

Calling superclass methods

  expand (n) {
    return super.expand(n) * Math.PI
  }
 

Static methods

  static createFromDiameter(diameter) {
    return new Circle(diameter / 2)
  }
}
 

Syntactic sugar for prototypes. See: Classes

Exponent operator

const byte = 2 ** 8
// Same as: Math.pow(2, 8)
 

#Promises

Making promises

new Promise((resolve, reject) => {
  if (ok) { resolve(result) }
  else { reject(error) }
})
 

For asynchronous programming. See: Promises

Using promises

promise
  .then((result) => { ··· })
  .catch((error) => { ··· })
 
 

Using promises with finally

promise
  .then((result) => { ··· })
  .catch((error) => { ··· })
  .finally(() => { // logic independent of success/error })
 

The handler is called when the promise is fulfilled or rejected.

Promise functions

Promise<span class="token punctuation">.</span><span class="token function">all</span><span class="token punctuation">(</span>···<span class="token punctuation">)</span>
Promise<span class="token punctuation">.</span><span class="token function">race</span><span class="token punctuation">(</span>···<span class="token punctuation">)</span>
Promise<span class="token punctuation">.</span><span class="token function">reject</span><span class="token punctuation">(</span>···<span class="token punctuation">)</span>
Promise<span class="token punctuation">.</span><span class="token function">resolve</span><span class="token punctuation">(</span>···<span class="token punctuation">)</span>

Async-await

async function run () {
  const user = await getUser()
  const tweets = await getTweets(user)
  return [user, tweets]
}
 
 

async functions are another way of using functions.

See: async function

#Destructuring

Destructuring assignment

Arrays

const [first, last] = ['Nikola', 'Tesla']
 

Objects

let {title, author} = {
  title: 'The Silkworm',
  author: 'R. Galbraith'
}
 

Supports for matching arrays and objects. See: Destructuring

Default values

<span class="token keyword">const</span> scores <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">22</span><span class="token punctuation">,</span> <span class="token number">33</span><span class="token punctuation">]</span>
<span class="token keyword">const</span> <span class="token punctuation">[</span>math <span class="token operator">=</span> <span class="token number">50</span><span class="token punctuation">,</span> sci <span class="token operator">=</span> <span class="token number">50</span><span class="token punctuation">,</span> arts <span class="token operator">=</span> <span class="token number">50</span><span class="token punctuation">]</span> <span class="token operator">=</span> scores
<span class="token comment" spellcheck="true">// Result:</span>
<span class="token comment" spellcheck="true">// math === 22, sci === 33, arts === 50</span>

Default values can be assigned while destructuring arrays or objects.

Function arguments

function greet({ name, greeting }) {
  console.log(`${greeting}, ${name}!`)
}
 
<span class="token function">greet</span><span class="token punctuation">(</span><span class="token punctuation">{</span> name<span class="token punctuation">:</span> <span class="token string">'Larry'</span><span class="token punctuation">,</span> greeting<span class="token punctuation">:</span> <span class="token string">'Ahoy'</span> <span class="token punctuation">}</span><span class="token punctuation">)</span>

Destructuring of objects and arrays can be also be done in function arguments.

Default values

function greet({ name = 'Rauno' } = {}) {
  console.log(`Hi ${name}!`);
}
 
<span class="token function">greet</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// Hi Rauno!</span>
<span class="token function">greet</span><span class="token punctuation">(</span><span class="token punctuation">{</span> name<span class="token punctuation">:</span> <span class="token string">'Larry'</span> <span class="token punctuation">}</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// Hi Larry!</span>

Reassigning keys

function printCoordinates({ left: x, top: y }) {
  console.log(`x: ${x}, y: ${y}`)
}
 
<span class="token function">printCoordinates</span><span class="token punctuation">(</span><span class="token punctuation">{</span> left<span class="token punctuation">:</span> <span class="token number">25</span><span class="token punctuation">,</span> top<span class="token punctuation">:</span> <span class="token number">90</span> <span class="token punctuation">}</span><span class="token punctuation">)</span>

This example assigns x to the value of the left key.

Loops

for (let {title, artist} of songs) {
  ···
}
 

The assignment expressions work in loops, too.

Object destructuring

const { id, ...detail } = song;
 

Extract some keys individually and remaining keys in the object using rest (…) operator

#Spread

Object spread

with Object spread

const options = {
  ...defaults,
  visible: true
}
 

without Object spread

<span class="token keyword">const</span> options <span class="token operator">=</span> Object<span class="token punctuation">.</span><span class="token function">assign</span><span class="token punctuation">(</span>
  <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">,</span> defaults<span class="token punctuation">,</span>
  <span class="token punctuation">{</span> visible<span class="token punctuation">:</span> <span class="token boolean">true</span> <span class="token punctuation">}</span><span class="token punctuation">)</span>

The Object spread operator lets you build new objects from other objects.

See: Object spread

Array spread

with Array spread

const users = [
  ...admins,
  ...editors,
  'rstacruz'
]
 
 

without Array spread

<span class="token keyword">const</span> users <span class="token operator">=</span> admins
  <span class="token punctuation">.</span><span class="token function">concat</span><span class="token punctuation">(</span>editors<span class="token punctuation">)</span>
  <span class="token punctuation">.</span><span class="token function">concat</span><span class="token punctuation">(</span><span class="token punctuation">[</span> <span class="token string">'rstacruz'</span> <span class="token punctuation">]</span><span class="token punctuation">)</span>

The spread operator lets you build new arrays in the same way.

See: Spread operator

#Functions

Function arguments

Default arguments

function greet (name = 'Jerry') {
  return `Hello ${name}`
}
 

Rest arguments

function fn(x, ...y) {
  // y is an Array
  return x * y.length
}
 

Spread

fn(...[1, 2, 3])
// same as fn(1, 2, 3)
 

Default, rest, spread. See: Function arguments

Fat arrows

Fat arrows

setTimeout(() => {
  ···
})
 

With arguments

readFile('text.txt', (err, data) => {
  ...
})
 

Implicit return

numbers.map(n => n * 2)
// No curly braces = implicit return
// Same as: numbers.map(function (n) { return n * 2 })
numbers.map(n => ({
  result: n * 2
})
// Implicitly returning objects requires parentheses around the object
 
 
 
 

Like functions but with this preserved. See: Fat arrows

#Objects

Shorthand syntax

module<span class="token punctuation">.</span>exports <span class="token operator">=</span> <span class="token punctuation">{</span> hello<span class="token punctuation">,</span> bye <span class="token punctuation">}</span>
<span class="token comment" spellcheck="true">// Same as: module.exports = { hello: hello, bye: bye }</span>

See: Object literal enhancements

Methods

const App = {
  start () {
    console.log('running')
  }
}
// Same as: App = { start: function () {···} }
 

See: Object literal enhancements

Getters and setters

const App = {
  get closed () {
    return this.status === 'closed'
  },
  set closed (value) {
    this.status = value ? 'closed' : 'open'
  }
}
 
 

See: Object literal enhancements

Computed property names

let event = 'click'
let handlers = {
  [`on${event}`]: true
}
// Same as: handlers = { 'onclick': true }
 

See: Object literal enhancements

Extract values

<span class="token keyword">const</span> fatherJS <span class="token operator">=</span> <span class="token punctuation">{</span> age<span class="token punctuation">:</span> <span class="token number">57</span><span class="token punctuation">,</span> name<span class="token punctuation">:</span> <span class="token string">"Brendan Eich"</span> <span class="token punctuation">}</span>

Object<span class="token punctuation">.</span><span class="token function">values</span><span class="token punctuation">(</span>fatherJS<span class="token punctuation">)</span>
<span class="token comment" spellcheck="true">// [57, "Brendan Eich"]</span>
Object<span class="token punctuation">.</span><span class="token function">entries</span><span class="token punctuation">(</span>fatherJS<span class="token punctuation">)</span>
<span class="token comment" spellcheck="true">// [["age", 57], ["name", "Brendan Eich"]]</span>

#Modules

Imports

<span class="token keyword">import</span> <span class="token string">'helpers'</span>
<span class="token comment" spellcheck="true">// aka: require('···')</span>
<span class="token keyword">import</span> Express <span class="token keyword">from</span> <span class="token string">'express'</span>
<span class="token comment" spellcheck="true">// aka: const Express = require('···').default || require('···')</span>
<span class="token keyword">import</span> <span class="token punctuation">{</span> indent <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'helpers'</span>
<span class="token comment" spellcheck="true">// aka: const indent = require('···').indent</span>
<span class="token keyword">import</span> <span class="token operator">*</span> <span class="token keyword">as</span> Helpers <span class="token keyword">from</span> <span class="token string">'helpers'</span>
<span class="token comment" spellcheck="true">// aka: const Helpers = require('···')</span>
<span class="token keyword">import</span> <span class="token punctuation">{</span> indentSpaces <span class="token keyword">as</span> indent <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'helpers'</span>
<span class="token comment" spellcheck="true">// aka: const indent = require('···').indentSpaces</span>

import is the new require(). See: Module imports

Exports

<span class="token keyword">export</span> <span class="token keyword">default</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> ··· <span class="token punctuation">}</span>
<span class="token comment" spellcheck="true">// aka: module.exports.default = ···</span>
<span class="token keyword">export</span> <span class="token keyword">function</span> mymethod <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> ··· <span class="token punctuation">}</span>
<span class="token comment" spellcheck="true">// aka: module.exports.mymethod = ···</span>
<span class="token keyword">export</span> <span class="token keyword">const</span> pi <span class="token operator">=</span> <span class="token number">3.14159</span>
<span class="token comment" spellcheck="true">// aka: module.exports.pi = ···</span>

export is the new module.exports. See: Module exports

#Generators

Generators

<span class="token keyword">function</span><span class="token operator">*</span> idMaker <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">let</span> id <span class="token operator">=</span> <span class="token number">0</span>
  <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token keyword">yield</span> id<span class="token operator">++</span> <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">let</span> gen <span class="token operator">=</span> <span class="token function">idMaker</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
gen<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>value  <span class="token comment" spellcheck="true">// → 0</span>
gen<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>value  <span class="token comment" spellcheck="true">// → 1</span>
gen<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>value  <span class="token comment" spellcheck="true">// → 2</span>

It’s complicated. See: Generators

For..of iteration

<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> i <span class="token keyword">of</span> iterable<span class="token punctuation">)</span> <span class="token punctuation">{</span>
  ···
<span class="token punctuation">}</span>