分割代入は、変数の要素やオブジェクトの値を展開して、個別の変数に代入する構文です。
配列を分割代入
let [a, b] = [1, 2];
console.log(a); //=> 1
console.log(b); //=> 2
不要な値を無視する。
2番目の値は不要なので、変数に代入しません。
let [a, , c] = [1, 2, 3];
console.log(a); //=> 1
console.log(c); //=> 3
オブジェクトを分割代入
let {a, b} = {a:1, b:2};
console.log(a); //=> 1
console.log(b); //=> 2
オブジェクトのプロパティ名と異なる変数名に代入する場合の書き方です。
let {a:x, b} = {a:1, b:2};
console.log(x); //=> 1
console.log(b); //=> 2
デフォルト値
変数名の後ろにデフォルト値を指定できます。
let {a=100, b=200} = {a:1};
console.log(a); //=> 1
console.log(b); //=> 200
関数の引数にデフォルト値を指定する
function func({a=100, b=200} = {}) {
console.log(a);
console.log(b);
}
func({a:30});
実行結果は次のようになります。
30
200
関数が複数の返値を返す
関数から複数の値を返したいとき、関数は配列で値を返し、受け取り側は分割代入を使うと簡潔に記述できます。
function func() {
return [100, 200];
}
let [a, b] = func();
console.log(a); //=> 100
console.log(b); //=> 200