1
2

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のmap、filter、コールバック引数名について

1
Posted at

今回はJavaScriptのmap()について学習したことをまとめました。
さらに、コールバック関数の引数名をどう決めればいいのか迷うことがありそれについてもまとめてみました。

テキストや学習サイトで模範解答と違う名前を使ったら不正解になってしまい、「これって自由に決めていいの?」と混乱した経験がある方も多いのではないでしょうか。

filter()の使い方を例に、「決まっている名前」と「自由に決めてよい名前」の合わせて違いを整理します。

💡map()とは

map()は配列の全要素に対して同じ処理を行い、新しい配列を返すメソッドです。

const prices = [1000, 2000, 3000, 4000];
const doubledPrices = prices.map((price) => price * 2);
console.log(doubledPrices) // [2000, 4000, 6000, 8000]

👉️2つの書き方

1行の処理なら{}returnを省略できます(implicit return)。

// シンプルな書き方(implicit return)
prices.map((price) => price * 2)

// {}を使う書き方(block body)※複数行処理や if文が必要なときに使う
prices.map((price) => {
  return price * 2;
})

❗️引数名の注意点

配列名と引数名を同じにするのは可読性の面でNGです。

// NG:外側のarrと内側のarrが紛らわしい
arr.map((arr) => arr * 1.5)

// OK
arr.map((value) => value * 1.5)
arr.map(v => v * 1.5)  // 最短の書き方

💡決まっている名前 vs 自分で決める名前

種類 理由
決まっている filterborn JavaScriptが用意したもの・自分が定義したキー
自由に決める personstarx どこにも登場していない新しい名前

見分けるシンプルな基準:「この名前、どこかで出てきた?」

出てきていない → 自由に決めてよい引数名

💡引数名は自分で自由に決めてよい

更にfilterなどの配列メソッドを使うとき、コールバック関数の引数名は自由に命名できます。

// 全部同じ意味
stars.filter((person) => person.born < 1990)
stars.filter((star)   => star.born < 1990)
stars.filter((x)      => x.born < 1990)

personという名前が使われているのは「配列の要素が人物だから」という可読性の理由だけです。

💡filter()の使い方

filter()は配列から条件に合う要素だけを取り出すメソッドです。

const stars = [
  { name: 'Hayao Miyazaki', born: 1941 },
  { name: 'Justin Bieber', born: 1994 },
  { name: 'Yuzuru Hanyu', born: 1998 },
  { name: 'Mariah Carey', born: 1969 },
  { name: 'Naomi Osaka', born: 1997 }
]

const filteredStars = stars.filter((person) => person.born < 1990)
console.log(filteredStars)
// [{ name: 'Hayao Miyazaki', born: 1941 }, { name: 'Mariah Carey', born: 1969 }]

filterは配列の要素を1つずつ取り出してコールバック関数に渡します。personには毎回オブジェクトが1つ入ってきます。
先程の引数名と同様(person)などは自由に命名することは可能です。
もちろん可読性の観点から、そのオブジェクトから想起させられる名前が望ましいです。

✅️テキストの模範解答と異なる引数名でも正解

テキストの採点システムは文字列の一致でチェックしていることが多いですが、引数名が違ってもプログラムとしては正しいので混乱しないように参考にしてみてください!

1
2
0

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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?