[JS] .map(), .forEach(), .reduce() 무엇을 언제 써야할까?

김상연·2022년 3월 17일

JavaScript

목록 보기
2/19

When to use forEach?

.forEach() is great you need to execute a function for each individual element in an array. Good practice is that you should use .forEach() when you can’t use other array methods to accomplish your goal. I know this may sound vague, but .forEach() is a generic tool… only use it when you can’t use a more specialized tool.

When to use map?

.map() when you want to transform elements in an array.

When to use filter?

.filter() when you want to select a subset of multiple elements from an array.

When to use find?

.find() When you want to select a single element from an array.

When to use reduce?

.reduce() when you want derive a single value from multiple elements in an array.

요지는,
.forEach()는 보다 일반적인 경우에만 이용하라는 것이다. map이나 reduce가 적합한 경우라면 그런 specialized tool을 사용하고. 어떤 method를 사용하는지를 통해 코드의 행간을 읽을 수 있을 것이다.

출처:
https://medium.com/@JeffLombardJr/understanding-foreach-map-filter-and-find-in-javascript-f91da93b9f2c


ps.내가 짧지 않은 시간 동안, 여러 프로젝트를 진행 해 왔다지만 사실 JS 개념은 기본 중의 기본만 알고 있었다. 묘사하자면 호미로 집을 지었달까? 이것도 나름 능력이라고 할 수도 있지만...

하여튼 프로젝트에서 잠시 벗어날 겸, 개념 공부를 하고있다. 유투브에 코딩앙마님의 js기초와 js중급을 듣고 있다. 중급을 30번 정도 반복한 뒤엔 typescript까지 익힐 생각이다.

찬씨의 점잖은 지적 덕분에 나의 코드가 엄청나게 절차 지향적이라는 것을 깨달았다. 나도 oop 스타일로 효율적으로, 머리 싸메지 않고 개발 및 보수하기 위해서는 typecript와 mongoDB를 배우는 것이 급선무다.

profile
리눅스와 컴퓨터 프로그래밍

0개의 댓글