1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JavaScript】構造分解(分割代入)

Last updated at Posted at 2025-09-03

はじめに

コードをきれいに書くために欠かせない構造分解(分割代入)について解説します。

2025/09/04 追記
MDNというウェブ開発者向けの技術ドキュメントサイトには以下のように「構造分解」という表現になっていましたので、こちらを主として「分割代入」を併記します。

構造分解(分割代入)とは

配列やオブジェクトから値を取り出してそれぞれに代入することを言います。

配列の構造分解(分割代入)

以下のような「hoge」という配列の変数があった場合、

const hoge = [1, 2, 3];

「hoge」の中に入ってた配列の値を、新しく定義した「one」、「two」、「three」という変数にそれぞれ代入できます。

const [one, two, three] = hoge;

console.log(one);
console.log(two);
console.log(three);

//出力結果
1
2
3

オブジェクトの構造分解(分割代入)

以下のような「hoge」というキー(プロパティ)と値が入った変数があった場合、

const hoge = { name: "dog", age: 2 };

「hoge」の中に入っていたオブジェクトのプロパティを取り出して、中に入っていた値を出力することが出来ます。

const { name, age } = hoge;

console.log(name);
console.log(age);

//出力結果
dog
2

変数名を変更したい場合は、まずプロパティ名とコロン(:)を書いた後に新しい変数を定義します。

const { name:getName, age:getAge } = hoge;

console.log(getName);
console.log(getAge);

//出力結果
dog
2

おわりに

個人的に理解するのにちょっと時間がかかった構文でした。

1
0
2

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?