JavaScript에서 일급 함수
Source: Dev.to
소개
JavaScript를 배우는 개발자들에게 일급 함수라는 용어는 토론과 문서에서 자주 등장합니다. JavaScript에서 함수는 일급 시민이며, 다른 값과 동일하게 취급됩니다. 문자열을 변수에 저장하거나 다른 함수에 전달할 수 있듯이, 함수도 저장하고, 전달하고, 반환할 수 있습니다.
일급 함수의 핵심 개념
변수를 통한 함수 저장
const washCarrot = function (carrot) {
return `${carrot} is now clean!`;
};
console.log(washCarrot('Orange carrot')); // "Orange carrot is now clean!"
함수를 인수로 전달하기
function prepareVegetable(veggie, quantity, prepMethod) {
return prepMethod(veggie, quantity);
}
const chop = (veg, qty) => `Chopped ${qty} ${veg}`;
const steam = (veg, qty) => `Steamed ${qty} ${veg}`;
console.log(prepareVegetable('broccoli', 3, chop)); // "Chopped 3 broccoli"
console.log(prepareVegetable('carrots', 5, steam)); // "Steamed 5 carrots"
함수에서 함수를 반환하기
function createVeggieCounter(vegetable) {
return function (quantity) {
return `You have ${quantity} ${vegetable}`;
};
}
const countTomatoes = createVeggieCounter('tomatoes');
const countCucumbers = createVeggieCounter('cucumbers');
console.log(countTomatoes(12)); // "You have 12 tomatoes"
console.log(countCucumbers(8)); // "You have 8 cucumbers"
객체 안에 함수 정리하기
const kitchenTasks = {
wash: (veggie) => `Washing ${veggie}`,
peel: (veggie) => `Peeling ${veggie}`,
slice: (veggie) => `Slicing ${veggie}`
};
console.log(kitchenTasks.wash('spinach')); // "Washing spinach"
실용적인 활용
map과 filter 같은 배열 메서드는 전적으로 일급 함수에 의존하며, 이벤트 핸들러, 콜백, 프로미스, 그리고 많은 함수형 프로그래밍 패턴도 마찬가지입니다.
const vegetables = ['carrot', 'broccoli', 'spinach', 'tomato', 'cucumber'];
const upperCaseVeggies = vegetables.map(veggie => veggie.toUpperCase());
// ['CARROT', 'BROCCOLI', 'SPINACH', 'TOMATO', 'CUCUMBER']
const longNameVeggies = vegetables.filter(veggie => veggie.length > 6);
// ['broccoli', 'spinach', 'cucumber']
장점
일급 함수는 JavaScript에 놀라운 유연성을 제공합니다. 다른 데이터와 마찬가지로 함수를 이동하고, 변형하고, 결합할 수 있어 코드가 더 깔끔하고 모듈화됩니다. 이 개념을 이해하면 많은 JavaScript 패턴이 명확해지고, 언어의 전체적인 힘을 활용할 수 있습니다.
잠재적 함정
같은 유연성이 부주의하게 사용될 경우 문제를 일으킬 수 있습니다:
- 메모리 누수 – 제거되지 않은 이벤트 리스너가 남아 있는 경우.
- 콜백 지옥 – 깊게 중첩된 콜백으로 가독성이 떨어지는 경우.
- 예기치 않은 클로저 – 의도보다 많은 상태를 캡처해 미묘한 버그를 유발하는 경우.
- 성능 문제 – 루프 안이나 자주 호출되는 코드에서 많은 함수 인스턴스를 생성하는 경우.
이러한 위험을 인식하면 개발자가 일급 함수를 책임감 있게 사용할 수 있습니다.
결론
일급 함수는 현대 JavaScript 개발의 기본 토대입니다. React와 같은 프레임워크, 프로미스를 이용한 비동기 코드, 이벤트 중심 프로그래밍 모두 함수가 값으로 취급되는 것에 의존합니다. 이 개념을 마스터하면 개발자는 더 표현력 있고 유지보수가 쉬우며 강력한 JavaScript 코드를 작성할 수 있습니다.