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

Hyejin·2023년 2월 19일
0

Javascript

목록 보기
1/4
post-thumbnail

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.
/*forEach method syntax*/
let myArray = [1, 2, 3, 4];
const returnValue = myArray.forEach((element) => {
	return element * element;
});
console.log(returnValue); //Output: undefined

/*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]

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()
1The forEach() method does not returns a new array based on the given array.The map() method returns an entirely new array.
2The forEach() method returns “undefined“.The map() method returns the newly created array according to the provided callback function.
3The 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.
4It 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

0개의 댓글