05/12/2024, 11:57 ES2015+ cheatsheet
Design and Development
your inbox. Every weekda
ES2015+ cheatsheet
ads via Carbon
A quick overview of new JavaScript features in ES2015, ES2016, ES2017, ES2018 and beyond.
Block scoping New methods
Let New string methods
function fn () { "hello".repeat(3)
let x = 0 "hello".includes("ll")
if (true) { "hello".startsWith("he")
let x = 1 // only inside this `if` "hello".padStart(8) // " hello"
} "hello".padEnd(8) // "hello "
} "hello".padEnd(8, '!') // hello!!!
"\u1E9B\u0323".normalize("NFC")
Const
const a = 1 See: New methods
let is the new var. Constants work just like let, but can’t be reassigned. See: Let and
const
Classes
class Circle extends Shape {
Backtick strings
Constructor
Interpolation
constructor (radius) {
const message = `Hello ${name}` this.radius = radius
}
Multiline strings
Methods
const str = `
hello getArea () {
world return Math.PI * 2 * this.radius
` }
Calling superclass methods
Templates and multiline strings. See: Template strings
expand (n) {
return super.expand(n) * Math.PI
}
Binary and octal literals Static methods
static createFromDiameter(diameter) {
let bin = 0b1010010 return new Circle(diameter / 2)
let oct = 0o755 }
}
See: Binary and octal literals
Syntactic sugar for prototypes. See: Classes
https://devhints.io/es6 1/5
05/12/2024, 11:57 ES2015+ cheatsheet
Exponent operator
const byte = 2 ** 8
// Same as: Math.pow(2, 8)
Promises
Making promises Using promises with finally Async-await
new Promise((resolve, reject) => { promise async function run () {
if (ok) { resolve(result) } .then((result) => { ··· }) const user = await getUser()
else { reject(error) } .catch((error) => { ··· }) const tweets = await getTweets(user)
}) .finally(() => { // logic independent of success/e return [user, tweets]
}
For asynchronous programming. See: Promises
The handler is called when the promise is fulfilled or async functions are another way of using functions.
rejected.
See: async function
Using promises
Promise functions
promise
.then((result) => { ··· })
.catch((error) => { ··· }) Promise.all(···)
Promise.race(···)
Promise.reject(···)
Promise.resolve(···)
Destructuring
Destructuring assignment Default values Function arguments
Arrays
const scores = [22, 33] function greet({ name, greeting }) {
const [first, last] = ['Nikola', 'Tesla'] const [math = 50, sci = 50, arts = 50] = scores console.log(`${greeting}, ${name}!`)
}
Objects
// Result:
// math === 22, sci === 33, arts === 50 greet({ name: 'Larry', greeting: 'Ahoy' })
let {title, author} = {
title: 'The Silkworm',
author: 'R. Galbraith' Default values can be assigned while destructuring Destructuring of objects and arrays can also be done in
} arrays or objects. function arguments.
Supports for matching arrays and objects.
See: Destructuring
https://devhints.io/es6 2/5
05/12/2024, 11:57 ES2015+ cheatsheet
Default values Reassigning keys Loops
function greet({ name = 'Rauno' } = {}) { function printCoordinates({ left: x, top: y }) { for (let {title, artist} of songs) {
console.log(`Hi ${name}!`); console.log(`x: ${x}, y: ${y}`) ···
} } }
greet() // Hi Rauno! printCoordinates({ left: 25, top: 90 }) The assignment expressions work in loops, too.
greet({ name: 'Larry' }) // Hi Larry!
This example assigns x to the value of the left key.
Object destructuring
const { id, ...detail } = song;
Extract some keys individually and remaining keys in
the object using rest (…) operator
Spread
Object spread Array spread
with Object spread with Array spread
const options = { const users = [
...defaults, ...admins,
visible: true ...editors,
} 'rstacruz'
]
without Object spread
without Array spread
const options = Object.assign(
{}, defaults, const users = admins
{ visible: true }) .concat(editors)
.concat([ 'rstacruz' ])
The Object spread operator lets you build new objects from other objects.
The spread operator lets you build new arrays in the same way.
See: Object spread
See: Spread operator
Functions
https://devhints.io/es6 3/5
05/12/2024, 11:57 ES2015+ cheatsheet
Function arguments Fat arrows
Default arguments Fat arrows
function greet (name = 'Jerry') { setTimeout(() => {
return `Hello ${name}` ···
} })
Rest arguments With arguments
function fn(x, ...y) { readFile('text.txt', (err, data) => {
// y is an Array ...
return x * y.length })
}
Implicit return
Spread
numbers.map(n => n * 2)
fn(...[1, 2, 3]) // No curly braces = implicit return
// same as fn(1, 2, 3) // Same as: numbers.map(function (n) { return n * 2 })
numbers.map(n => ({
result: n * 2
Default, rest, spread. See: Function arguments
}))
// Implicitly returning objects requires parentheses around the object
Like functions but with this preserved. See: Fat arrows
Objects
Shorthand syntax Getters and setters
module.exports = { hello, bye } const App = {
// Same as: module.exports = { hello: hello, bye: bye } get closed () {
return this.status === 'closed'
},
See: Object literal enhancements
set closed (value) {
this.status = value ? 'closed' : 'open'
}
}
Methods
See: Object literal enhancements
const App = {
start () {
console.log('running')
}
Computed property names
}
// Same as: App = { start: function () {···} }
let event = 'click'
let handlers = {
See: Object literal enhancements [`on${event}`]: true
}
// Same as: handlers = { 'onclick': true }
See: Object literal enhancements
https://devhints.io/es6 4/5
05/12/2024, 11:57 ES2015+ cheatsheet
Extract values
const fatherJS = { age: 57, name: "Brendan Eich" }
Object.values(fatherJS)
// [57, "Brendan Eich"]
Object.entries(fatherJS)
// [["age", 57], ["name", "Brendan Eich"]]
Modules
Imports Exports
import 'helpers' export default function () { ··· }
// aka: require('···') // aka: module.exports.default = ···
import Express from 'express' export function mymethod () { ··· }
// aka: const Express = require('···').default || require('···') // aka: module.exports.mymethod = ···
import { indent } from 'helpers' export const pi = 3.14159
// aka: const indent = require('···').indent // aka: module.exports.pi = ···
import * as Helpers from 'helpers' export is the new module.exports. See: Module exports
// aka: const Helpers = require('···')
import { indentSpaces as indent } from 'helpers'
// aka: const indent = require('···').indentSpaces
import is the new require(). See: Module imports
Generators
Generators For..of iteration
function* idMaker () { for (let i of iterable) {
let id = 0 ···
while (true) { yield id++ } }
}
For iterating through generators and arrays. See: For..of iteration
let gen = idMaker()
gen.next().value // → 0
gen.next().value // → 1
gen.next().value // → 2
It’s complicated. See: Generators
https://devhints.io/es6 5/5