cheatsheets/es6.md

579 lines
9.2 KiB
Markdown
Raw Permalink Normal View History

2015-01-20 15:10:15 +00:00
---
2017-08-28 19:18:32 +00:00
title: ES2015+
2015-11-24 05:02:17 +00:00
category: JavaScript
2017-08-28 19:18:32 +00:00
tags: [Featured]
2020-07-05 11:11:36 +00:00
updated: 2019-11-14
2017-08-29 16:38:47 +00:00
weight: -10
2017-10-10 15:47:03 +00:00
intro: |
A quick overview of new JavaScript features in ES2015, ES2016, ES2017, ES2018 and beyond.
2015-01-20 15:10:15 +00:00
---
2017-10-02 05:17:28 +00:00
### Block scoping
2015-02-06 09:41:03 +00:00
2017-10-02 05:17:28 +00:00
#### Let
2015-02-06 09:41:03 +00:00
2015-02-24 08:13:25 +00:00
```js
2015-02-06 09:41:03 +00:00
function fn () {
2017-08-27 15:55:33 +00:00
let x = 0
2015-02-06 09:41:03 +00:00
if (true) {
2017-08-27 15:55:33 +00:00
let x = 1 // only inside this `if`
2015-02-06 09:41:03 +00:00
}
}
2015-03-11 10:50:57 +00:00
```
2017-08-27 15:55:33 +00:00
{: data-line="2,4"}
2015-02-06 09:41:03 +00:00
2017-10-02 05:17:28 +00:00
#### Const
2015-03-11 10:50:57 +00:00
```js
2017-08-27 15:55:33 +00:00
const a = 1
2015-02-24 08:13:25 +00:00
```
2015-02-06 09:41:03 +00:00
2017-10-05 16:12:07 +00:00
`let` is the new `var`. Constants work just like `let`, but can't be reassigned.
See: [Let and const](https://babeljs.io/learn-es2015/#let--const)
2017-08-27 15:55:33 +00:00
### Backtick strings
2015-02-06 09:41:03 +00:00
2017-10-02 05:17:28 +00:00
#### Interpolation
2015-02-24 08:13:25 +00:00
```js
const message = `Hello ${name}`
2015-03-11 10:50:57 +00:00
```
2015-02-06 09:41:03 +00:00
2017-10-02 05:17:28 +00:00
#### Multiline strings
2015-03-11 10:50:57 +00:00
```js
const str = `
2015-02-24 08:13:25 +00:00
hello
world
2017-08-27 15:55:33 +00:00
`
2015-02-24 08:13:25 +00:00
```
2017-08-27 15:55:33 +00:00
Templates and multiline strings.
See: [Template strings](https://babeljs.io/learn-es2015/#template-strings)
2015-02-24 08:13:25 +00:00
2017-08-27 15:55:33 +00:00
### Binary and octal literals
2015-02-06 09:41:03 +00:00
2015-03-11 10:50:57 +00:00
```js
2017-08-27 15:55:33 +00:00
let bin = 0b1010010
2017-10-07 20:15:12 +00:00
let oct = 0o755
2015-02-06 09:41:03 +00:00
```
See: [Binary and octal literals](https://babeljs.io/learn-es2015/#binary-and-octal-literals)
2015-02-25 07:55:54 +00:00
2017-08-27 15:55:33 +00:00
### New methods
2015-02-25 07:55:54 +00:00
2017-10-02 05:17:28 +00:00
#### New string methods
2015-03-11 10:50:57 +00:00
```js
2017-08-27 15:55:33 +00:00
"hello".repeat(3)
"hello".includes("ll")
2018-05-11 16:14:59 +00:00
"hello".startsWith("he")
"hello".padStart(8) // " hello"
"hello".padEnd(8) // "hello "
"hello".padEnd(8, '!') // hello!!!
2017-08-27 15:55:33 +00:00
"\u1E9B\u0323".normalize("NFC")
2015-02-25 07:55:54 +00:00
```
See: [New methods](https://babeljs.io/learn-es2015/#math--number--string--object-apis)
2015-03-11 12:10:05 +00:00
2017-08-27 15:55:33 +00:00
### Classes
2015-05-06 04:01:36 +00:00
```js
class Circle extends Shape {
2017-10-02 05:17:28 +00:00
```
#### Constructor
```js
2017-08-27 15:55:33 +00:00
constructor (radius) {
this.radius = radius
2015-05-06 04:01:36 +00:00
}
2017-10-02 05:17:28 +00:00
```
{: data-line="1"}
#### Methods
2015-05-06 04:01:36 +00:00
2017-10-02 05:17:28 +00:00
```js
2017-08-27 15:55:33 +00:00
getArea () {
return Math.PI * 2 * this.radius
2015-05-06 04:01:36 +00:00
}
2017-10-02 05:17:28 +00:00
```
{: data-line="1"}
#### Calling superclass methods
2015-05-06 04:01:36 +00:00
2017-10-02 05:17:28 +00:00
```js
2017-08-27 15:55:33 +00:00
expand (n) {
return super.expand(n) * Math.PI
2015-05-06 04:01:36 +00:00
}
2017-10-02 05:17:28 +00:00
```
2017-10-11 17:04:27 +00:00
{: data-line="2"}
2017-10-02 05:17:28 +00:00
#### Static methods
2015-05-06 04:01:36 +00:00
2017-10-02 05:17:28 +00:00
```js
2015-05-06 04:01:36 +00:00
static createFromDiameter(diameter) {
2017-08-27 15:55:33 +00:00
return new Circle(diameter / 2)
2015-05-06 04:01:36 +00:00
}
}
```
2017-10-02 05:17:28 +00:00
{: data-line="1"}
2015-05-06 04:01:36 +00:00
2017-08-27 15:55:33 +00:00
Syntactic sugar for prototypes.
See: [Classes](https://babeljs.io/learn-es2015/#classes)
2015-02-06 09:41:03 +00:00
2017-10-02 05:17:28 +00:00
### Exponent operator
```js
const byte = 2 ** 8
// Same as: Math.pow(2, 8)
```
{: data-line="1"}
Promises
--------
{: .-three-column}
### Making promises
```js
new Promise((resolve, reject) => {
if (ok) { resolve(result) }
else { reject(error) }
})
```
{: data-line="1"}
For asynchronous programming.
See: [Promises](https://babeljs.io/learn-es2015/#promises)
2017-10-02 05:17:28 +00:00
### Using promises
```js
promise
.then((result) => { ··· })
.catch((error) => { ··· })
```
{: data-line="2,3"}
### Using promises with finally
```js
promise
.then((result) => { ··· })
.catch((error) => { ··· })
.finally(() => { // logic independent of success/error })
```
{: data-line="4"}
The handler is called when the promise is fulfilled or rejected.
2017-10-02 05:17:28 +00:00
### Promise functions
```js
Promise.all(···)
Promise.race(···)
Promise.reject(···)
Promise.resolve(···)
```
### Async-await
```js
async function run () {
const user = await getUser()
const tweets = await getTweets(user)
return [user, tweets]
}
```
{: data-line="2,3"}
`async` functions are another way of using functions.
See: [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)
2017-10-02 05:17:28 +00:00
Destructuring
-------------
{: .-three-column}
### Destructuring assignment
#### Arrays
2015-02-06 09:42:04 +00:00
2015-02-24 08:13:25 +00:00
```js
const [first, last] = ['Nikola', 'Tesla']
2015-03-11 10:50:57 +00:00
```
2017-10-26 06:33:50 +00:00
{: data-line="1"}
2015-02-06 09:42:04 +00:00
2017-10-02 05:17:28 +00:00
#### Objects
2015-03-11 10:50:57 +00:00
```js
2017-10-02 05:17:28 +00:00
let {title, author} = {
title: 'The Silkworm',
author: 'R. Galbraith'
2015-02-06 09:42:04 +00:00
}
2015-03-11 10:50:57 +00:00
```
2017-10-02 05:17:28 +00:00
{: data-line="1"}
Supports for matching arrays and objects.
See: [Destructuring](https://babeljs.io/learn-es2015/#destructuring)
2017-10-02 05:17:28 +00:00
### Default values
```js
const scores = [22, 33]
const [math = 50, sci = 50, arts = 50] = scores
```
2017-10-26 06:33:50 +00:00
```js
// Result:
// math === 22, sci === 33, arts === 50
```
Default values can be assigned while destructuring arrays or objects.
2017-10-02 05:17:28 +00:00
### Function arguments
2015-02-06 09:41:03 +00:00
2015-03-11 10:50:57 +00:00
```js
2015-02-24 07:42:45 +00:00
function greet({ name, greeting }) {
2017-10-02 05:17:28 +00:00
console.log(`${greeting}, ${name}!`)
2015-02-24 07:42:45 +00:00
}
2017-10-02 05:17:28 +00:00
```
{: data-line="1"}
2015-02-24 07:42:45 +00:00
2017-10-02 05:17:28 +00:00
```js
2017-08-27 16:01:37 +00:00
greet({ name: 'Larry', greeting: 'Ahoy' })
2015-02-24 08:13:25 +00:00
```
2017-08-27 15:55:33 +00:00
2019-09-21 14:13:48 +00:00
Destructuring of objects and arrays can also be done in function arguments.
2018-03-17 05:33:08 +00:00
### Default values
```js
2018-03-17 05:33:08 +00:00
function greet({ name = 'Rauno' } = {}) {
console.log(`Hi ${name}!`);
}
```
{: data-line="1"}
```js
2018-03-17 05:33:08 +00:00
greet() // Hi Rauno!
greet({ name: 'Larry' }) // Hi Larry!
```
### Reassigning keys
```js
function printCoordinates({ left: x, top: y }) {
console.log(`x: ${x}, y: ${y}`)
}
2017-10-02 05:17:28 +00:00
```
{: data-line="1"}
2015-02-24 07:42:45 +00:00
2017-10-02 05:17:28 +00:00
```js
printCoordinates({ left: 25, top: 90 })
2015-02-24 08:13:25 +00:00
```
2017-08-27 15:55:33 +00:00
This example assigns `x` to the value of the `left` key.
2017-10-02 05:17:28 +00:00
### Loops
2017-08-31 05:01:05 +00:00
```js
for (let {title, artist} of songs) {
2017-10-02 05:17:28 +00:00
···
}
2017-08-31 05:01:05 +00:00
```
{: data-line="1"}
2017-10-21 05:36:56 +00:00
The assignment expressions work in loops, too.
2017-10-02 05:17:28 +00:00
### Object destructuring
```js
const { id, ...detail } = song;
```
{: data-line="1"}
2018-11-20 06:18:50 +00:00
Extract some keys individually and remaining keys in the object using rest (...) operator
Spread
------
### Object spread
#### with Object spread
```js
const options = {
...defaults,
visible: true
}
```
{: data-line="2"}
#### without Object spread
```js
const options = Object.assign(
{}, defaults,
{ visible: true })
```
The Object spread operator lets you build new objects from other objects.
See: [Object spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator)
### Array spread
2017-10-24 03:12:16 +00:00
#### with Array spread
```js
const users = [
...admins,
...editors,
'rstacruz'
]
```
{: data-line="2,3"}
2017-10-24 03:12:16 +00:00
#### without Array spread
```js
const users = admins
.concat(editors)
.concat([ 'rstacruz' ])
```
The spread operator lets you build new arrays in the same way.
See: [Spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator)
2017-08-27 15:55:33 +00:00
Functions
---------
### Function arguments
2015-02-24 08:13:25 +00:00
2017-10-02 05:17:28 +00:00
#### Default arguments
2015-02-24 08:13:25 +00:00
```js
function greet (name = 'Jerry') {
2017-08-27 15:55:33 +00:00
return `Hello ${name}`
2015-02-06 09:41:03 +00:00
}
2015-03-11 10:50:57 +00:00
```
2017-10-02 05:17:28 +00:00
{: data-line="1"}
#### Rest arguments
2015-02-06 09:41:03 +00:00
2015-03-11 10:50:57 +00:00
```js
2015-02-06 09:41:03 +00:00
function fn(x, ...y) {
// y is an Array
2017-08-27 15:55:33 +00:00
return x * y.length
2015-02-06 09:41:03 +00:00
}
2015-03-11 10:50:57 +00:00
```
2017-10-02 05:17:28 +00:00
{: data-line="1"}
#### Spread
2015-02-06 09:41:03 +00:00
2015-03-11 10:50:57 +00:00
```js
2017-08-31 05:01:05 +00:00
fn(...[1, 2, 3])
// same as fn(1, 2, 3)
2015-02-24 08:13:25 +00:00
```
2017-10-02 05:17:28 +00:00
{: data-line="1"}
2015-02-24 08:13:25 +00:00
2017-08-27 15:55:33 +00:00
Default, rest, spread.
See: [Function arguments](https://babeljs.io/learn-es2015/#default--rest--spread)
2017-08-27 15:55:33 +00:00
### Fat arrows
2015-02-06 09:41:03 +00:00
2017-10-02 05:17:28 +00:00
#### Fat arrows
2015-02-24 08:13:25 +00:00
```js
2015-02-06 09:41:03 +00:00
setTimeout(() => {
2017-10-02 05:17:28 +00:00
···
2017-08-27 15:55:33 +00:00
})
2015-03-11 12:06:22 +00:00
```
2017-10-02 05:17:28 +00:00
{: data-line="1"}
#### With arguments
2015-03-11 12:06:22 +00:00
```js
readFile('text.txt', (err, data) => {
...
2017-08-27 15:55:33 +00:00
})
2015-03-11 10:50:57 +00:00
```
2017-10-02 05:17:28 +00:00
{: data-line="1"}
2015-02-06 09:41:03 +00:00
2017-10-02 05:17:28 +00:00
#### Implicit return
2015-03-11 10:50:57 +00:00
```js
2015-02-24 08:13:25 +00:00
numbers.map(n => n * 2)
2017-10-02 05:17:28 +00:00
// No curly braces = implicit return
2017-08-27 15:55:33 +00:00
// Same as: numbers.map(function (n) { return n * 2 })
numbers.map(n => ({
result: n * 2
}))
// Implicitly returning objects requires parentheses around the object
2015-02-24 08:13:25 +00:00
```
{: data-line="1,4,5,6"}
2015-02-24 07:49:13 +00:00
2017-08-27 15:55:33 +00:00
Like functions but with `this` preserved.
See: [Fat arrows](https://babeljs.io/learn-es2015/#arrows-and-lexical-this)
2017-08-27 15:55:33 +00:00
Objects
-------
### Shorthand syntax
```js
module.exports = { hello, bye }
2017-08-27 16:01:37 +00:00
// Same as: module.exports = { hello: hello, bye: bye }
2017-08-27 15:55:33 +00:00
```
See: [Object literal enhancements](https://babeljs.io/learn-es2015/#enhanced-object-literals)
2017-08-27 15:55:33 +00:00
### Methods
```js
const App = {
start () {
console.log('running')
}
}
2017-08-27 16:01:37 +00:00
// Same as: App = { start: function () {···} }
2017-08-27 15:55:33 +00:00
```
{: data-line="2"}
See: [Object literal enhancements](https://babeljs.io/learn-es2015/#enhanced-object-literals)
2017-08-27 15:55:33 +00:00
### Getters and setters
```js
const App = {
get closed () {
return this.status === 'closed'
},
set closed (value) {
2017-10-26 06:26:06 +00:00
this.status = value ? 'closed' : 'open'
2017-08-27 15:55:33 +00:00
}
}
```
{: data-line="2,5"}
See: [Object literal enhancements](https://babeljs.io/learn-es2015/#enhanced-object-literals)
2017-08-27 15:55:33 +00:00
### Computed property names
```js
let event = 'click'
let handlers = {
[`on${event}`]: true
2017-08-27 15:55:33 +00:00
}
2017-08-27 16:01:37 +00:00
// Same as: handlers = { 'onclick': true }
2017-08-27 15:55:33 +00:00
```
{: data-line="3"}
See: [Object literal enhancements](https://babeljs.io/learn-es2015/#enhanced-object-literals)
2017-08-27 15:55:33 +00:00
### Extract values
```js
const fatherJS = { age: 57, name: "Brendan Eich" }
Object.values(fatherJS)
// [57, "Brendan Eich"]
Object.entries(fatherJS)
// [["age", 57], ["name", "Brendan Eich"]]
```
{: data-line="3,5"}
2017-08-27 15:55:33 +00:00
Modules
-------
### Imports
```js
import 'helpers'
2017-08-27 16:01:37 +00:00
// aka: require('···')
2017-08-27 15:55:33 +00:00
```
```js
import Express from 'express'
// aka: const Express = require('···').default || require('···')
2017-08-27 15:55:33 +00:00
```
```js
import { indent } from 'helpers'
// aka: const indent = require('···').indent
2017-08-27 16:01:37 +00:00
```
```js
import * as Helpers from 'helpers'
// aka: const Helpers = require('···')
2017-08-27 15:55:33 +00:00
```
```js
import { indentSpaces as indent } from 'helpers'
// aka: const indent = require('···').indentSpaces
2017-08-27 15:55:33 +00:00
```
`import` is the new `require()`.
See: [Module imports](https://babeljs.io/learn-es2015/#modules)
2017-08-27 15:55:33 +00:00
### Exports
```js
2017-08-27 16:01:37 +00:00
export default function () { ··· }
2017-08-27 15:55:33 +00:00
// aka: module.exports.default = ···
```
```js
2017-08-27 16:01:37 +00:00
export function mymethod () { ··· }
2017-08-27 15:55:33 +00:00
// aka: module.exports.mymethod = ···
2017-08-27 16:01:37 +00:00
```
2017-08-27 15:55:33 +00:00
2017-08-27 16:01:37 +00:00
```js
export const pi = 3.14159
2017-08-27 15:55:33 +00:00
// aka: module.exports.pi = ···
```
2017-08-27 16:01:37 +00:00
`export` is the new `module.exports`.
See: [Module exports](https://babeljs.io/learn-es2015/#modules)
2017-08-27 15:55:33 +00:00
Generators
----------
### Generators
```js
2017-08-27 16:01:37 +00:00
function* idMaker () {
let id = 0
2017-08-27 15:55:33 +00:00
while (true) { yield id++ }
}
```
```js
let gen = idMaker()
2017-10-02 05:17:28 +00:00
gen.next().value // → 0
gen.next().value // → 1
gen.next().value // → 2
2017-08-27 15:55:33 +00:00
```
It's complicated.
See: [Generators](https://babeljs.io/learn-es2015/#generators)
2017-08-27 15:55:33 +00:00
### For..of iteration
2015-02-25 18:46:18 +00:00
2015-03-11 10:50:57 +00:00
```js
2015-07-27 01:24:44 +00:00
for (let i of iterable) {
2017-10-02 05:17:28 +00:00
···
2015-02-25 18:46:18 +00:00
}
```
2017-08-27 15:55:33 +00:00
For iterating through generators and arrays.
See: [For..of iteration](https://babeljs.io/learn-es2015/#iterators--forof)