LoginSignup
3
4

More than 3 years have passed since last update.

2019の終わりにES2019を覚えておく

Last updated at Posted at 2019-12-03

ES2015が世の中に浸透し始めたときには、必死こいて「このビッグウェーブに乗らなきゃ!」と人並みに勉強しましたが、それ以降の動向は追っていませんでした。ここのところ、年末ということもあってかES2019についての記事をちらほら見ることが増えて、今年のことは今年のうちに覚えておこう、という動機です。ES2016〜ES2018についても理解していませんが、それは来年まとめてやっつけます。

ES2019には何が含まれているのか、この互換性テーブルを見ると分かりやすいです。

互換性テーブルを元にES2019に追加された機能は次の通りです。

2019 features

  • Object.fromEntries
  • string trimming
  • Array.prototype.{flat, flatMap}

2019 misc

  • optional catch binding
  • Symbol.prototype.description
  • Function.prototype.toString revision
  • JSON superset
  • Well-formed JSON.stringify

今回は、この中で2019 featuresの3つ、2019 miscの中から覚えておくと良さそうな optional catch binding をピックアップして勉強します。

それではひとつひとつ何をするためのものなのか、ざっくりと見ていきます。

※本記事は理解力、読解力ともに難がある私自身が理解するために、かなり噛み砕いた文章になるので、文字を読むのが得意な方は互換性テーブルから各機能のリンク先を読むことをオススメします。

Object.fromEntries

Object.fromEntries() メソッドは、キーと値の組み合わせのリストをオブジェクトに変換します。
MDN:Object.fromEntries

const fruits = Object.fromEntries([['banana', 2], ['apple', 3]])
// {banana: 2, apple: 3}

参考:Object.fromEntries

string trimming

互換性テーブルを参考に、次の4つの機能について見ていきます。

  • String.prototype.trimLeft
  • String.prototype.trimRight
  • String.prototype.trimStart
  • String.prototype.trimEnd

String.prototype.trimLeftString.prototype.trimStart のエイリアス、String.prototype.trimRight は、 String.prototype.trimEnd のエイリアスなので、実質以下2つを覚えれば良いと解釈します。

  • String.prototype.trimStart
  • String.prototype.trimEnd

String.prototype.trimStart

先頭の空白を削除します。

const sample = '     こんにちは、世界よ     ';
console.log(sample.trimStart());
// 'こんにちは、世界よ     '

参考:String.prototype.trimStart

String.prototype.trimEnd

末尾の空白を削除します。

const sample = '     こんにちは、世界よ     ';
console.log(sample.trimEnd());
// '     こんにちは、世界よ'

参考:String.prototype.trimEnd

Array.prototype.{flat, flatMap}

Array.prototype.flat

ネストされた配列をフラットにします。

const arr1 = [1, 2, [3, 4]];
// [1, 2, 3, 4]

参考:Array.prototype.flat

Array.prototype.flatMap

map したものをフラットにしたい場合、Array.prototype.flatMap を使わないと、まず map してから flat 関数を使ってフラットにします。
しかし、 Array.prototype.flatMap を使うと、一つの関数でフラットにできます。

let arr1 = [1, 2, 3, 4];

const arr2 = arr1.map(x => [x * 2]).flat(); 
// [2, 4, 6, 8]

const arr3 = arr1.flatMap(x => [x * 2]);
// [2, 4, 6, 8]

参考:Array.prototype.flatMap

optional catch binding

バインディングが使用されない場合にキャッチバインディングを省略できる、というものです。
つまり、try-catchは通常次のようになりますが、

try {
} catch(e) {
}

バインディングを使用しない場合は、記述を省略できるという文法の変更です。

try {
} catch {
}

参考:optional catch binding

終わりに

ES2019だけにフォーカスすれば量としてはそんなに多くなかったのですが、勉強していなかったES2016〜2018をまとめてインプットするのは中々ヘビーだなという印象です。次回はES2016にフォーカスして勉強してみようと思います。

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4