Programming/Javascript

JavaScript 고차함수 Higher-Order Functions 콜백함수 Callback Functions

makeitworth 2020. 11. 18. 13:22

higher-order function은 파라미터로 함수를 받는 함수 / 함수 위의 함수

callback function 파라미터에 들어가는 함수 / 불려오는 함수

 

const func = () => console.log("func");

const timeFuncRuntime = funcParameter => {
    console.log('funcParameter');
    funcParameter();
    return 1;
};
console.log(timeFuncRuntime(func));

결과는

funcParameter
func
1

코드 중간에 funcParameter();는 파라미터로 받은 함수를 실행하는 코드.

위 예에서는 파라미터로 받은 함수(=콜백함수) 는 그냥 로그로 func 찍는 함수이므로

func가 찍힘.

 

Codecademy 예제는 (출처: 코드카데미)

 

콜백함수

const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
  for(let i = 1; i <= 1000000; i++) {
    if ( (2 + 2) != 4) {
      console.log('Something has gone very wrong :( ');
    }
  }
};

고차함수

const timeFuncRuntime = funcParameter => {
  let t1 = Date.now();
  funcParameter();
  let t2 = Date.now();
  return t2 - t1;
};

 

const time2p2 =  timeFuncRuntime(checkThatTwoPlusTwoEqualsFourAMillionTimes);
console.log(time2p2);

결과값은 

나왔음

 

 

 

만일 고차 함수로 짜지 않고 한 번에 표현한다면, 이렇게 복잡해졌을 것임

const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
    let t1 = Date.now();
    for(let i = 1; i <= 1000000; i++) {
        if ( (2 + 2) != 4) {
            console.log('Something has gone very wrong :( ');
        }
    }
    let t2 = Date.now();
    console.log(t2-t1);
};

 

 

 

 

*참고*

 

Higher-Order Function 이란 무엇인가

[Javascript] 고차함수와 콜백함수