27
17

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

JavaScriptの便利な関数機能と構文まとめ

(デフォルト引数、スプレッド構文、レスト構文、分割代入)


1. デフォルト引数(Default Parameters)

関数の引数に値が渡されなかった場合やundefinedだった場合に、あらかじめ設定したデフォルト値を使えます。

function rollDie(numSides = 6) {
  return Math.floor(Math.random() * numSides) + 1;
}

console.log(rollDie());    // 1〜6のランダムな数
console.log(rollDie(20));  // 1〜20のランダムな数

ポイント

  • 引数を省略しても関数が動くようにできる
  • デフォルト値は任意の型や式を指定可能

2. スプレッド構文(Spread Syntax)

配列やオブジェクトの要素を展開(分解)するための構文です。

配列の展開

const nums = [1, 2, 3, 4, 5];

console.log(nums);      // [1, 2, 3, 4, 5]
console.log(...nums);   // 1 2 3 4 5 (個別の値として展開)

複数の配列を結合

const cats = ['Tama', 'Tora', 'Momo'];
const dogs = ['Rex', 'Buddy', 'Max'];

const allPets = [...cats, ...dogs];
console.log(allPets);
// ['Tama', 'Tora', 'Momo', 'Rex', 'Buddy', 'Max']

オブジェクトの展開

const feline = { legs: 4, family: 'ネコ科' };
const canine = { family: 'イヌ科', bark: true };

const catDog = {
  ...feline,
  ...canine,
};

console.log(catDog);
// { legs: 4, family: 'イヌ科', bark: true }
// 後のプロパティで上書きされるので family は 'イヌ科' になる

3. レスト構文(Rest Parameters)

複数の引数をまとめて1つの配列として受け取ることができます。

function sum(...nums) {
  console.log(nums);
  return nums.reduce((total, n) => total + n, 0);
}

console.log(sum(1, 2, 3));       // [1, 2, 3] → 6
console.log(sum(10, 20, 30, 40)); // [10, 20, 30, 40] → 100

ポイント

  • 関数の最後の引数に使う
  • 引数の数が不定でも対応可能

4. 分割代入(Destructuring)

配列やオブジェクトの値を簡潔に変数に展開できます。

配列の分割代入

const scores = [929321, 899341, 888336, 772739, 543671, 243567, 111934];

const [gold, silver, bronze, ...rest] = scores;

console.log(gold);    // 929321
console.log(silver);  // 899341
console.log(bronze);  // 888336
console.log(rest);    // [772739, 543671, 243567, 111934]

オブジェクトの分割代入

const user = {
  email: 'test@test.com',
  password: 'password',
  firstName: 'Test',
  lastName: 'User',
};

const { firstName, lastName, email } = user;

console.log(firstName); // Test
console.log(lastName);  // User
console.log(email);     // test@test.com

5. 関数パラメーターでの分割代入

関数の引数の中で分割代入を使って、必要なプロパティだけ受け取ることもできます。

function greetUser({ firstName, lastName }) {
  console.log(`こんにちは、${firstName} ${lastName}さん!`);
}

const user = {
  firstName: 'Taro',
  lastName: 'Yamada',
  age: 30,
};

greetUser(user);  // → こんにちは、Taro Yamadaさん!

まとめ

  • デフォルト引数は引数がない場合の安全策に
  • スプレッド構文は配列やオブジェクトの展開・結合に便利
  • レスト構文は複数の引数をまとめて扱うときに使う
  • 分割代入で変数の取り出しがシンプルに!
  • 関数パラメーターで分割代入を使うと必要な値だけすぐ受け取れてコードがスッキリする
27
17
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
27
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?