A quick reference to JavaScript features introduced in ES2015, ES2016, ES2017, ES2018 and later editions. Examples are independent syntax fragments; ellipses mark omitted application code.
Block scope
Let
function fn () {
let x = 0
if (true) {
let x = 1 // only inside this `if`
}
}
Const
const a = 1
let and const have block scope; var has function scope. const prevents reassignment but does not freeze objects. See: let and const
Template literals
Interpolation
const message = `Hello ${name}`
Multiline strings
const str = `
hello
world
`
Templates support interpolation and multiline text. See: Template strings
Binary and octal literals
let bin = 0b1010010
let oct = 0o755
See: Binary and octal literals
New methods
String methods
"hello".repeat(3)
"hello".includes("ll")
"hello".startsWith("he")
"hello".padStart(8) // " hello"
"hello".padEnd(8) // "hello "
"hello".padEnd(8, '!') // hello!!!
"\u1E9B\u0323".normalize("NFC")
See: New methods
Classes
class Shape {
constructor (radius) { this.radius = radius }
expand (n) { return this.radius * n }
}
class Circle extends Shape {
Constructor
constructor (radius) {
super(radius)
this.radius = radius
}
Methods
getArea () {
return Math.PI * this.radius ** 2
}
Calling a superclass method
expand (n) {
this.radius = super.expand(n)
return this
}
Static methods
static createFromDiameter(diameter) {
return new Circle(diameter / 2)
}
}
Class syntax builds on JavaScript prototypes. These fragments form one class example; the derived constructor calls super before accessing this. See: Classes
Exponentiation
const byte = 2 ** 8
// Same as: Math.pow(2, 8)
Promises
Creating a Promise
new Promise((resolve, reject) => {
if (ok) { resolve(result) }
else { reject(error) }
})
Promises represent asynchronous completion or failure. See: Promises
Using a Promise
promise
.then((result) => { ··· })
.catch((error) => { ··· })
Using finally
promise
.then((result) => { ··· })
.catch((error) => { ··· })
.finally(() => { /* logic independent of success/error */ })
A fulfillment handler receives the result; a rejection handler receives the error. finally runs after settlement without receiving either value.
Promise helpers
Promise.all(···)
Promise.race(···)
Promise.reject(···)
Promise.resolve(···)
Async-await
async function run () {
const user = await getUser()
const tweets = await getTweets(user)
return [user, tweets]
}
An async function returns a Promise; await suspends that function until its operand settles.
See: Async functions
Destructuring
Destructuring assignment
Arrays
const [first, last] = ['Nikola', 'Tesla']
Objects
let {title, author} = {
title: 'The Silkworm',
author: 'R. Galbraith'
}
Destructuring extracts values from arrays and properties from objects. See: Destructuring
Default values
const scores = [22, 33]
const [math = 50, sci = 50, arts = 50] = scores
// Result:
// math === 22, sci === 33, arts === 50
Defaults apply when the extracted value is undefined, not null.
Function parameters
function greet({ name, greeting }) {
console.log(`${greeting}, ${name}!`)
}
greet({ name: 'Larry', greeting: 'Ahoy' })
Function parameters can destructure arrays and objects.
Default values
function greet({ name = 'Rauno' } = {}) {
console.log(`Hi ${name}!`);
}
greet() // Hi Rauno!
greet({ name: 'Larry' }) // Hi Larry!
Renaming properties
function printCoordinates({ left: x, top: y }) {
console.log(`x: ${x}, y: ${y}`)
}
printCoordinates({ left: 25, top: 90 })
This assigns the left property to local variable x and top to y.
Loops
for (let {title, artist} of songs) {
···
}
Destructuring patterns also work in loop bindings.
ObjectsDestructuring
const { id, ...detail } = song;
Object rest collects the remaining own enumerable properties after selected properties have been extracted.
Spread
Object spread
With object spread
const options = {
...defaults,
visible: true
}
Without object spread
const options = Object.assign(
{}, defaults,
{ visible: true })
Object spread creates a shallow copy of enumerable own properties; later properties overwrite earlier ones.
See: Object spread
Array spread
With array spread
const users = [
...admins,
...editors,
'rstacruz'
]
Without array spread
const users = admins
.concat(editors)
.concat([ 'rstacruz' ])
Array spread creates a new array from iterable values.
See: Spread syntax
Functions
Function parameters
Default parameters
function greet (name = 'Jerry') {
return `Hello ${name}`
}
Rest parameters
function fn(x, ...y) {
// y is an Array
return x * y.length
}
Spread
fn(...[1, 2, 3])
// same as fn(1, 2, 3)
Default parameters, rest parameters and argument spread. See: Function parameters
Arrow functions
Arrow functions
setTimeout(() => {
···
})
With parameters
readFile('text.txt', (err, data) => {
...
})
Implicit returns
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
Arrow functions capture this from the surrounding scope and cannot be used as constructors. See: Arrow functions
Objects
Property shorthand
module.exports = { hello, bye }
// Same as: module.exports = { hello: hello, bye: bye }
Methods
const App = {
start () {
console.log('running')
}
}
// Same as: App = { start: function () {···} }
Getters and setters
const App = {
get closed () {
return this.status === 'closed'
},
set closed (value) {
this.status = value ? 'closed' : 'open'
}
}
Computed property names
let event = 'click'
let handlers = {
[`on${event}`]: true
}
// Same as: handlers = { 'onclick': true }
Values and entries
const fatherJS = { age: 57, name: "Brendan Eich" }
Object.values(fatherJS)
// [57, "Brendan Eich"]
Object.entries(fatherJS)
// [["age", 57], ["name", "Brendan Eich"]]
Modules
Imports
import 'helpers'
// aka: require('···')
import Express from 'express'
// aka: const Express = require('···').default || require('···')
import { indent } from 'helpers'
// aka: const indent = require('···').indent
import * as Helpers from 'helpers'
// aka: const Helpers = require('···')
import { indentSpaces as indent } from 'helpers'
// aka: const indent = require('···').indentSpaces
ES imports and CommonJS require are distinct module mechanisms. The comments illustrate related use cases rather than exact runtime equivalence. See: Module imports
Exports
export default function () { ··· }
// aka: module.exports.default = ···
export function mymethod () { ··· }
// aka: module.exports.mymethod = ···
export const pi = 3.14159
// aka: module.exports.pi = ···
export declares ES module exports; its semantics differ from CommonJS module.exports. See: Module exports
Generators
Generators
function* idMaker () {
let id = 0
while (true) { yield id++ }
}
let gen = idMaker()
gen.next().value // → 0
gen.next().value // → 1
gen.next().value // → 2
Generators return iterators and pause at yield. See: Generators
For-of iteration
for (let i of iterable) {
···
}
for-of iterates the values produced by an iterable, including arrays and generators. See: For-of iteration
Collection helpers
const unique = [...new Set([1, 1, 2])];
const scores = new Map([["Ada", 10]]);
for (const [name, score] of scores) console.log(name, score);