[JavaScript] Array Methods- map() and forEach() function

2023. 2. 25. 22:14・Frontend/JavaScript

 

1️⃣ map() 와 forEach()의 공통점:

  • 모든 요소에 콜백함수를 호출
  • 각 요소를 순회하며 요소에 무언가를 할 수 있음

JavaScript .forEach() and .map(): These are the methods that are used to iterate on an array, more technically they invoke the provided callback function for every element of an array.

Syntax:

forEach((currentElement, indexOfElement, array) => { ... }
map((currentElement, indexOfElement, array) => { ... } )

Parameters:

  • currentElement: This is the current element that is being processed in the callback.
  • indexOfElement: The index of that current element inside the array.

array: The array on which the whole operation is being performed.

 

 

/*map method syntax*/ 
let myArray = [1, 2, 3, 4]; 
const returnValue = myArray.map((element) => { return element * element; }); 
console.log(returnValue); //Output: [1, 4, 9, 16]
/*forEach method syntax*/ 
let myArray = [1, 2, 3, 4]; 
const returnValue = myArray.forEach((element) => { 
	return element * element; 
}); 
console.log(returnValue); //Output: undefined

2️⃣ Chaining technique은 map()에서만 가능

  • forEach()는 반환값이 undefined, map()은 리턴값이 새로운 배열을 반환

In this example, we are going to apply the chaining technique, the return value is being operated on the next instance method. We have used the array reverse() method for simplicity but it can be anything i.e sort, find, reduce, filter, etc. Even custom methods can be used for chaining.

let myArray = [1, 2, 3, 4];
const returnValue = myArray.forEach((element) => {
    return element * element;
}).reverse();
console.log(returnValue); //👻 Error
/** Output:  The forEach() method is returning “undefined” and 
the next instance method(reverse) can be invoked by an array.  
TypeError is being thrown by JavaScript.
*/
  • forEach()에서 undefined이 반환, reverse()를 체이닝하면 에러가 난다.
let myArray = [1, 2, 3, 4];
const returnValue = myArray.map((element) => {
    return element * element;
}).reverse();
console.log(returnValue); //🙆🏻‍♀️ [16, 9, 4, 1]
/**
✅ Output: Here the map method returns an array that invokes 
the next instance method and which later provides 
the final returnValue(reverse of the invoking array).
*/
  • map()은 새로운 배열을 반환하여, 그 다음 인스턴스 메서드 reverse()를 호출

3️⃣ 그래서 map()과 forEach()의 차이점은:

  • forEach()는 undefined를 반환하므로 체이닝 기술을 적용할 수 없고, 빈 요소에는 실행되지 않음
  • map()은 콜백함수를 통해 새롭게 만들어진 배열을 반환하고, reduce(), sort() 같은 다른 메서드를 체이닝 할 수 있음. 원본 배열은 바뀌지 않음
forEach() map()
The forEach() method does not returns a new array based on the given array. The map() method returns an entirely new array.
The forEach() method returns “undefined“. The map() method returns the newly created array according to the provided callback function.
The forEach() method doesn’t return anything hence the method chaining technique cannot be applied here. With the map() method, we can chain other methods like, reduce(),sort() etc.
It is not executed for empty elements. It does not change the original array.

✅ Conclusion

  • Return value(=new array)를 가지고 chaning method 하거나, 원본 배열 변경하기 싫을 때 :
    map()

As they are working with very few differences, also the execution speed is not significant to consider so it is time to think about, which one to choose. If you want the benefits of the return value or somehow you don’t want to change the original array then proceed with the map() otherwise if you are just interested to iterate or perform the non-transformation process on the array, forEach() could be the better choice.

Reference:
Difference between forEach() and map() loop in JavaScript

저작자표시 비영리 변경금지 (새창열림)

'Frontend > JavaScript' 카테고리의 다른 글

[JavaScript] What is THIS  (0) 2022.03.15
Web APIs 란?  (0) 2021.02.20
'Frontend/JavaScript' 카테고리의 다른 글
  • [JavaScript] What is THIS
  • Web APIs 란?
dev.hyejin
dev.hyejin
  • dev.hyejin
    혜진의 개발자 성장블로그
    dev.hyejin
  • 전체
    오늘
    어제
    • 분류 전체보기 (89)
      • 2024 데브캠프 (2)
      • 회고 (1)
      • 이슈해결 (3)
      • 기초학습 (13)
      • Frontend (20)
        • JavaScript (3)
        • Git, GitHub (3)
        • HTML, CSS (14)
      • Backend (8)
        • Database (4)
        • Java (4)
      • CS (16)
        • Network (10)
        • Algorithm (6)
      • Eng (16)
      • Tips (5)
  • 인기 글

  • 태그

    객체
    절대경로
    GitHub
    상대경로
    런타임
    box-sizing
    시간복잡도
    border-box
    ER모델
    점근성능
  • hELLO· Designed By정상우.v4.10.3
dev.hyejin
[JavaScript] Array Methods- map() and forEach() function
상단으로

티스토리툴바