JavaScript

일급 함수와 고차 함수

ri5 2021. 11. 20. 17:16

일급 함수

함수를 다른 변수와 동일하게 다루는 언어를 일급 함수를 가졌다고 표현합니다.
함수를 다른 함수의 파라미터로 제공하거나, 함수가 함수를 반환 또는 변수에도 함수를 할당할 수 있습니다.  

변수에 함수 할당

const helloWorld = function() {
	console.log("hello World");
}

helloWorld(); //output: hello World

익명 함수를 변수에 할당하여 괄호를 통해 함수를 호출함.

함수를 인자로 전달

function hello() {
	return "hello, ";
}

function printHello(message, name){
	console.log(message() + name);
}

printHello(hello, "철수"); //output: hello, 철수

함수 반환

function sayHello() {
   return function() {
      console.log("Hello!");
   }
}

고차 함수(Higher-Order Function)

고차 함수란 함수를 인자로 받거나 함수를 반환함으로 써 작동하는 함수를 말합니다.
예를 들어 고차 함수는 function을 파라미터로 받거나 function을 output(출력)으로 리턴하는 함수입니다. 

고차 함수로 동작하지 않는 함수

const arr1 = [1, 2, 3];
const arr2 = [];

for(let i=0; i<arr1.length; i++) {
  arr2.push(arr1[i] * 2);
}

// prints [2, 4, 6]
console.log(arr2);

 

 

고차 함수로 작성

const arr1 = [1, 2, 3];

const arr2 = arr1.map(function(item) {
  return item * 2;
});

console.log(arr2); //output: [2, 4, 6]

 

람다 함수로 작성한다면 더 짧게 작성 가능

const arr1 = [1, 2, 3];

const arr2 = arr1.map(item => item * 2);

console.log(arr2); //output: [2, 4, 6]