ES2015、ES2016、ES2017、ES2018 以降に追加された JavaScript 機能の早見表です。各例は独立しており、省略記号はアプリケーションコードの省略を表します。
ブロックスコープ
Let
function fn () {
let x = 0
if (true) {
let x = 1 // only inside this `if`
}
}
Const
const a = 1
let と const はブロックスコープ、var は関数スコープです。 const は再代入を防ぎますが、オブジェクトは凍結しません。 let and const
テンプレートリテラル
補間
const message = `Hello ${name}`
複数行文字列
const str = `
hello
world
`
テンプレートでは補間と複数行の文字列を使えます。 Template strings
2 進数と 8 進数のリテラル
let bin = 0b1010010
let oct = 0o755
新しいメソッド
文字列メソッド
"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")
クラス
class Shape {
constructor (radius) { this.radius = radius }
expand (n) { return this.radius * n }
}
class Circle extends Shape {
コンストラクター
constructor (radius) {
super(radius)
this.radius = radius
}
メソッド
getArea () {
return Math.PI * this.radius ** 2
}
親クラスのメソッド呼び出し
expand (n) {
this.radius = super.expand(n)
return this
}
静的メソッド
static createFromDiameter(diameter) {
return new Circle(diameter / 2)
}
}
クラス構文は JavaScript のプロトタイプに基づきます。これらの断片は一つのクラス例です。派生クラスのコンストラクターは、this を使う前に super を呼び出します。 Classes
べき乗
const byte = 2 ** 8
// Same as: Math.pow(2, 8)
Promise
Promise を作成する
new Promise((resolve, reject) => {
if (ok) { resolve(result) }
else { reject(error) }
})
Promise は非同期処理の完了または失敗を表します。 Promises
Promise を使う
promise
.then((result) => { ··· })
.catch((error) => { ··· })
finally を使う
promise
.then((result) => { ··· })
.catch((error) => { ··· })
.finally(() => { /* logic independent of success/error */ })
成功時のハンドラーは結果を、失敗時のハンドラーはエラーを受け取ります。 finally は結果が確定した後に実行され、どちらの値も受け取りません。
Promise の補助メソッド
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]
}
async 関数は Promise を返します。 await はオペランドの結果が確定するまで関数の実行を一時停止します。
分割代入
分割代入の式
配列
const [first, last] = ['Nikola', 'Tesla']
オブジェクト
let {title, author} = {
title: 'The Silkworm',
author: 'R. Galbraith'
}
分割代入は配列の値やオブジェクトのプロパティを取り出します。 Destructuring
既定値
const scores = [22, 33]
const [math = 50, sci = 50, arts = 50] = scores
// Result:
// math === 22, sci === 33, arts === 50
既定値は取り出した値が undefined の場合に適用され、null には適用されません。
関数の引数
function greet({ name, greeting }) {
console.log(`${greeting}, ${name}!`)
}
greet({ name: 'Larry', greeting: 'Ahoy' })
関数の引数でも配列やオブジェクトを分割代入できます。
既定値
function greet({ name = 'Rauno' } = {}) {
console.log(`Hi ${name}!`);
}
greet() // Hi Rauno!
greet({ name: 'Larry' }) // Hi Larry!
プロパティ名の変更
function printCoordinates({ left: x, top: y }) {
console.log(`x: ${x}, y: ${y}`)
}
printCoordinates({ left: 25, top: 90 })
left はローカル変数 x に、top は y に代入されます。
ループ
for (let {title, artist} of songs) {
···
}
ループの変数宣言でも分割代入を使えます。
オブジェクトの分割代入
const { id, ...detail } = song;
オブジェクトの残余構文は、選択したプロパティを取り出した後に残った列挙可能な独自プロパティを集めます。
スプレッド構文
オブジェクトのスプレッド
スプレッドを使う場合
const options = {
...defaults,
visible: true
}
スプレッドを使わない場合
const options = Object.assign(
{}, defaults,
{ visible: true })
オブジェクトのスプレッドは列挙可能な独自プロパティを浅くコピーします。後に指定したプロパティは前の値を上書きします。
配列のスプレッド
スプレッドを使う場合
const users = [
...admins,
...editors,
'rstacruz'
]
スプレッドを使わない場合
const users = admins
.concat(editors)
.concat([ 'rstacruz' ])
配列のスプレッドは反復可能な値から新しい配列を作ります。
関数
関数の引数
既定値付き引数
function greet (name = 'Jerry') {
return `Hello ${name}`
}
残余引数
function fn(x, ...y) {
// y is an Array
return x * y.length
}
スプレッド構文
fn(...[1, 2, 3])
// same as fn(1, 2, 3)
既定値付き引数、残余引数、引数のスプレッドを示します。 Function parameters
アロー関数
アロー関数
setTimeout(() => {
···
})
引数付き
readFile('text.txt', (err, data) => {
...
})
暗黙の戻り値
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
アロー関数は外側のスコープの this を使い、コンストラクターには使えません。 Arrow functions
オブジェクト
プロパティの短縮記法
module.exports = { hello, bye }
// Same as: module.exports = { hello: hello, bye: bye }
メソッド
const App = {
start () {
console.log('running')
}
}
// Same as: App = { start: function () {···} }
ゲッターとセッター
const App = {
get closed () {
return this.status === 'closed'
},
set closed (value) {
this.status = value ? 'closed' : 'open'
}
}
計算されたプロパティ名
let event = 'click'
let handlers = {
[`on${event}`]: true
}
// Same as: handlers = { 'onclick': true }
値とエントリー
const fatherJS = { age: 57, name: "Brendan Eich" }
Object.values(fatherJS)
// [57, "Brendan Eich"]
Object.entries(fatherJS)
// [["age", 57], ["name", "Brendan Eich"]]
モジュール
インポート
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 モジュールのインポートと CommonJS の require は異なる仕組みです。コメントでは用途を比較しており、実行時の動作が同じという意味ではありません。 Module imports
エクスポート
export default function () { ··· }
// aka: module.exports.default = ···
export function mymethod () { ··· }
// aka: module.exports.mymethod = ···
export const pi = 3.14159
// aka: module.exports.pi = ···
export は ES モジュールのエクスポートを宣言します。CommonJS の module.exports とは意味が異なります。 Module exports
ジェネレーター
ジェネレーター
function* idMaker () {
let id = 0
while (true) { yield id++ }
}
let gen = idMaker()
gen.next().value // → 0
gen.next().value // → 1
gen.next().value // → 2
ジェネレーターはイテレーターを返し、yield で一時停止します。 Generators
for-of による反復
for (let i of iterable) {
···
}
for-of は、配列やジェネレーターなどの反復可能オブジェクトが返す値を順に処理します。 For-of iteration
コレクションの補助機能
const unique = [...new Set([1, 1, 2])];
const scores = new Map([["Ada", 10]]);
for (const [name, score] of scores) console.log(name, score);