0
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

forEachとmapの違い

Last updated at Posted at 2022-11-16

結論、戻り値を持つかどうかです。

const arr = [本田, 香川, 岡崎, 内田, 長友];

// forEachの場合
arr.forEach(value => {
  console.log(value);
});
// 本田
// 香川
// 岡崎
// 内田
// 長友


// mapの場合
arr.map(value => {
  console.log(value)
});
// 本田
// 香川
// 岡崎
// 内田
// 長友

forEachもmapも得られる結果は同じ。

大きく異なる点は、戻り値を持つかどうか

const arr = [本田, 香川, 岡崎, 内田, 長友];

// forEachの場合
const forEachResult = arr.forEach(value => {
  return value;
});
console.log(forEachResult); 
// undefined

// mapの場合
const mapResult = arr.map(value => {
  return value;
});
console.log(mapResult);
// [本田, 香川, 岡崎, 内田, 長友]
0
4
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
0
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?