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】分割代入を理解する

Posted at

分割代入とは

分割代入は、配列やオブジェクトの値を簡潔に変数へ代入できる構文です。コードの可読性を高め、記述量を減らすことができます。

基本的な使い方

配列の分割代入

配列の要素を複数の変数に一度に代入できます。

const point = [10, 20];
const [x, y] = point;

console.log(x); // 10
console.log(y); // 20

オブジェクトの分割代入

オブジェクトのプロパティを変数に代入できます。実務で頻繁に使われるパターンです。

const user = { name: "Alice", age: 25 };
const { name, age } = user;

console.log(name); // "Alice"
console.log(age);  // 25

応用テクニック

変数名の変更

コロン記法を使うことで、元のプロパティ名とは異なる変数名を指定できます。

const user = { name: "Alice", age: 25 };
const { name: userName, age: userAge } = user;

console.log(userName); // "Alice"
console.log(userAge);  // 25

デフォルト値の設定

値が存在しない場合に使用されるデフォルト値を設定できます。

const point = [10];
const [x, y = 0] = point;

console.log(x); // 10
console.log(y); // 0

関数パラメータでの活用

関数の引数で分割代入を使うと、必要なプロパティだけを明示的に受け取れます。

function greet({ name, age }) {
  console.log(`Hello, my name is ${name} and I am ${age} years old.`);
}

greet({ name: "Bob", age: 30 });
// Hello, my name is Bob and I am 30 years old.

処理の流れ

まとめ

分割代入を使うことで、以下のメリットが得られます。

  • コードの記述量が減る
  • 変数の意味が明確になる
  • 関数の引数が読みやすくなる

実務では特にオブジェクトの分割代入が多用されるため、積極的に活用してみましょう。

1
0
1

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?