forEach vs map

Jeong Ha Seung·2022년 3월 9일
// Example of forEach()

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

arr.forEach(num => {
  mulArr.push(num * 3);
});

console.log(mulArr); // [3, 6, 9, 12, 15]
// Example of map()

const arr = [1, 2, 3, 4, 5];
const mulArr = arr.map(num => num * 3);

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

forEach()가 배열 요소마다 한 번씩 주어진 함수(콜백)를 실행하며, 기존 배열을 변경하는 반면

map()은 배열 내의 모든 요소 각각에 대하여 주어진 함수(콜백)를 호출한 결과를 모아 새로운 배열을 반환한다는 특징을 가지고 있다.

출처 : https://dream-frontend.tistory.com/341

profile
블로그 이전했습니다. https://morethan-haseung-log.vercel.app

0개의 댓글