JavaScript

[JavaScript] map과 forEach 그리고 둘의 차이점

반응형

1. map

map은 굉장히 많이 쓰이는 메소드로 배열을 하나하나 돌며 처리할 작업이 있을 경우 사용됩니다.

 

기본 구조는 다음과 같습니다.

array.map((currentValue, index, array) => {
  // callback Function
}, thisArg)

currentValue : 현재 array내의 값

index : 현재 array 값의 인덱스

array : map이 돌고있는 array 자체

thisArg : 콜백함수 내에서의 this

 

예제

const array = [10, 20, 30, 40, 50]

array.map((a, b, c) => {
  console.log(a)
  console.log(b)
  console.log(c)
})

// 10
// 0
// [ 10, 20, 30, 40, 50 ]

// 20
// 1
// [ 10, 20, 30, 40, 50 ]

// 30
// 2
// [ 10, 20, 30, 40, 50 ]

// 40
// 3
// [ 10, 20, 30, 40, 50 ]

// 50
// 4
// [ 10, 20, 30, 40, 50 ]

 

현재값, 인덱스, 배열 이 순서로 array속의 갯수 5만큼 다섯번 콘솔에 찍히는 것을 알 수 있습니다.

 

2. forEach

array.forEach((currentValue, index, array) => {
  // callback Function
}, thisArg)

currentValue : 현재 array내의 값

index : 현재 array 값의 인덱스

array : map이 돌고있는 array 자체

thisArg : 콜백함수 내에서의 this

(map과 똑같습니다)

 

예제

const array = [10, 20, 30, 40, 50]

array.forEach((a, b, c) => {
  console.log(a)
  console.log(b)
  console.log(c)
})

// 10
// 0
// [ 10, 20, 30, 40, 50 ]

// 20
// 1
// [ 10, 20, 30, 40, 50 ]

// 30
// 2
// [ 10, 20, 30, 40, 50 ]

// 40
// 3
// [ 10, 20, 30, 40, 50 ]

// 50
// 4
// [ 10, 20, 30, 40, 50 ]

forEach를 사용해도 map을 사용한 것과 같은 값이 나오게됩니다. 그럼 이 두 메소드의 차이는 무엇일까요?

 

3. map과 forEach의 차이점

map과 forEach의 차이점은 map은 return값이 있지만 forEach는 return값이 없다는 점입니다.

 

다음 예시를 보겠습니다.

1. map

const array = [10, 20, 30, 40, 50]

const result = array.map((a) => {
  return a + 1
})

console.log(result) // [ 11, 21, 31, 41, 51 ]

 

2. forEach

const array = [10, 20, 30, 40, 50]

const result = array.forEach((a) => {
  return a + 1
})

console.log(result) // undefined

 

각 배열의 값에 1을 더하고 return 후 콘솔에 찍어보았습니다.

map은 콘솔에 잘 찍히는 반면 forEach는 undefined를 내뱉게 됩니다.

 

 

 

 

 

반응형