본문 바로가기
개발/Javascript

[Javascript] map() vs forEach()

by devhooney 2022. 9. 6.
728x90

내가 헷갈려서 한 번 정리하는 포스팅

 

array.forEach() vs array.map() 을 간단하게 비교해서 정리하려한다.

 

1. map()

- 콜백함수의 반환값들로 구성된 새로운 배열을 반환

- 원본배열을 변경하지 않음

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

const newArr = arr.map(i => {
	return i * 3;
});

console.log(newArr) // [3, 6, 9, 12, 15]

 

 

 

2. forEach()

- 조건문과 반복문을 제거하여 복잡성을 해결하고 변수의 사용을 억제하는 프로그래밍

- 단순 반복문을 대체하기 위함

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

const newArr = arr.forEach((num, index) => {
  return num*3 // or arr[index]*3;
})

console.log(newArr); // undefined

const newArr2 = arr.forEach(num => {
	return newArr2.push(num * 3);
})

console.log(newArr2) // [3, 6, 9, 12, 15]

 

- 구글링 결과 map()은 다른 메소드(filter(), reduce() 등)들과 연계하기 편하기 때문에 map()을 쓰는 편이 좋다고 한다.

- 성능도 더 좋다고함.

 

https://frontdev.tistory.com/entry/JS-Map-vs-ForEach

 

[JS] Map vs ForEach

Map vs ForEach 이 글은 https://codeburst.io/javascript-map-vs-foreach-f38111822c0f의 번역내용을 다수 포함하고 있습니다. JavaScript로 작업 해왔다면, Array.prototype.map ()과 Array.prototype.forEach (..

frontdev.tistory.com

 

728x90