はじめに
こんにちは。
JavaScriptでは、「分割代入(構造分解)」といって、配列やオブジェクトから値・プロパティを取り出して変数に代入する方法があります。
この記事では、JavaScriptの分割代入について調べたことをまとめます。
MDNでは、「構造分解(destructuring、旧: 分割代入)」という名前で説明されていますが、おそらく「分割代入」という呼び方が現在も主流ですので、これ以降は「分割代入」と記載します。
分割代入とは
分割代入について、MDNでは以下のように説明されています。
構造分解(destructuring、旧:分割代入)構文は、配列から値を取り出して、あるいはオブジェクトからプロパティを取り出して別個の変数に代入することを可能にする JavaScript の構文です。
つまり、配列やオブジェクトをそのまま使うのではなく、中にある値だけを取り出して変数として扱えるようにする書き方です。
配列の分割代入
まずは配列の分割代入について見てみましょう。
配列の分割代入では値は順番で取り出され、n番目の変数に配列のn番目の値が入ります。
const colors = ["red", "yellow", "green"];
const [color1, color2] = colors;
console.log(color1); //red
console.log(color2); //yellow
要素を飛ばす
配列の途中の要素を使わない場合は、カンマで飛ばすことができます。
const colors = ["red", "yellow", "green"];
const [color1, , color3] = colors;
console.log(color1); //red
console.log(color3); //green
この例では、2番目の "yellow" を飛ばして、1番目と3番目だけを取り出しています。
存在しない要素はundefinedになる
存在しない要素を取り出そうとした場合は undefined が入ります。
const colors = ["red"];
const [color1, color2] = colors;
console.log(color1); //red
console.log(color2); //undefined
この場合、colors には要素が1つしかありません。color1 には "red" が入りますが、color2 には undefined が入ります。
残りの要素をまとめて受け取る
配列の分割代入では、残余構文 ... を使って、残りの要素をまとめて受け取ることができます。
const colors = ["red", "yellow", "green", "blue"];
const [firstColor, ...otherColors] = colors;
console.log(firstColor);
console.log(otherColors);
firstColor には1番目の "red" が入り、otherColors には、残りの ["yellow", "green", "blue"] が配列として入ります。
実行結果は次のようになります。
red
[ 'yellow', 'green', 'blue' ]
オブジェクトの分割代入
次に、オブジェクトの分割代入を見てみましょう。
オブジェクトの分割代入では、プロパティ名で値を取り出します。次の例では、user.name が name に入り、user.age が age に入ります。
const user = {
id: 1,
name: "Alice",
age: 20,
};
const { name, age } = user;
console.log(name); //Alice
console.log(age); //20
次のようにプロパティアクセサーを用いてプロパティを取り出した場合と同じ挙動になります。
const name = user.name;
const age = user.age;
取り出すプロパティが多い場合は、一個一個 user.name、user.age のように書くよりも、分割代入で取り出す方が読みやすくなります。
変数名を変えて取り出す
オブジェクトの分割代入でも変数名を自由につけることができます。次の例を見てみましょう。
const user = {
id: 1,
name: "Alice",
};
const { name: userName } = user;
console.log(userName); //Alice
このコードでは、user の name プロパティを取り出して、userName という変数名で受け取っています。
デフォルト値を指定する
分割代入では、値がない(undefined)場合のデフォルト値も指定できます。
const user = {
name: "Alice",
};
const { name, age = 0 } = user;
console.log(name); //Alice
console.log(age); //0
user には age プロパティがないため、age = 0 のデフォルト値が使われます。
一方で、null の場合は undefined ではないため、デフォルト値は発動しません。
const user2 = { name: "Alice", age: null };
const { age: age2 = 0 } = user2;
console.log(age2); // null
残りのプロパティをまとめて受け取る
配列と同じように、オブジェクトの分割代入でも残余構文 ... が使えます。
const user = {
id: 1,
name: "Alice",
age: 20,
};
const { id, ...rest } = user;
console.log(id);
console.log(rest);
id には 1 が入り、rest には id 以外のプロパティがまとめてオブジェクトとして入ります。
実行結果は次のようになります。
1
{ name: 'Alice', age: 20 }
ネストした分割代入
オブジェクトが入れ子になっている場合も、分割代入で一気に値を取り出すことができます。
const data = {
user: {
name: "Alice",
address: {
city: "Tokyo",
},
},
};
const {
user: {
name,
address: { city },
},
} = data;
console.log(name); //Alice
console.log(city); //Tokyo
nullやundefinedを分割代入するとエラーになる
オブジェクトの分割代入では、対象が null や undefined だとエラーになります。
const { name } = undefined;
// TypeError: Cannot destructure property 'name' of 'undefined' as it is undefined.
const { name } = null;
// 同様にTypeError
関数の引数でも使われる
分割代入は、関数の引数でも用いることができます。
function showUser({ name, age }) {
console.log(`${name}さんは${age}歳です`);
}
const user = {
name: "Alice",
age: 20,
};
showUser(user); //Aliceさんは20歳です
この例では、showUser() に user オブジェクトを渡し、関数側で name と age を取り出しています。
まとめ
- 分割代入は、配列やオブジェクトから値を取り出して変数に入れる構文
- 配列の分割代入は、順番 で値を取り出す
- オブジェクトの分割代入は、プロパティ名 で値を取り出す
-
nullやundefinedを分割代入しようとするとエラーになる
お読みいただきありがとうございました。