개발자

[javascript] First-class function

지구빵집 2022. 12. 29. 09:53
반응형

 

 

 

프로그래밍 언어에서 다른 변수들처럼 다루어지는 함수를 일급함수라고 합니다. 예를 들어, 다른함수의 인자로 전달되기도하고, 함수에서 반환이 되기도 하며, 변수에 대입(assign)이 될 수 있습니다. 

 

다음은 일급함수의 조건입니다.

  • 변수나 데이터 구조안에 담을수 있다.
  • 파라미터로 전달 할 수 있다.
  • 반환값으로 사용할 수 있다.
  • 할당에 사용된 이름과 관계없이 고유한 구별이 가능하다
  • 동적으로 프로퍼티 할당이 가능하다. 

 

변수에 대입하여 사용 가능

 

//익명함수를 변수에 대입 가능합니다.
const foo = function() {
  console.log("foobar");
};

// 변수끝에 ()를 붙여 함수를 실행할 수 있습니다.
foo();

 

함수를 인자로 전달 가능: value로서 함수를 다루는 방법입니다. 함수의 인자로서 전달되는 함수를 "콜백함수" 라고 불립니다. 

 

function sayHello() {
  return "Hello, ";
}
function greeting(helloMessage, name) {
  
  //인자로 전달받은 함수를 실행할 수 있습니다.
  console.log(helloMessage() + name);
}

//함수를 인자로 전달할 수 있습니다.
greeting(sayHello, "JavaScript!");

 

함수 반환(Return a function) : 함수를 인자로 받아 사용하거나 함수를 반환하는 함수를 Higher-Order Function 라고 합니다. 

 

const sayHello = function() {
  //자바스크립트에서 `Value`로 다루어지기때문에 함수를 반환 할 수 있습니다.
  return function() {
    console.log("Hello!");
  }
}

//사용법1
const myFunc = sayHello();
myFunc(); //반환된 함수를 실행

//사용법2
sayHello()(); //반환된함수를 바로 실행

 

예제 코드

 

// First-class function
// functions are treated like any other variable
// can be assigned as a value to variable
// can be passed as an argument to other functions.
// can be returned by another function

// 1. Function expression
// a function declaration can be called earlier than it is defined. (hoisted)
// a function expression is created when the execution reaches it.
const print = function () {
  // anonymous function
  console.log('print');
};

function sum(a, b) {
  return a + b;
}

print();
const printAgain = print;
printAgain();
const sumAgain = sum;
console.log(sumAgain(1, 3)); // 4

// 2. Callback function using function expression
function randomQuiz(answer, printYes, printNo) {
  if (answer === 'love you') {
    printYes();
  } else {
    printNo();
  }
}
// anonymous function
const printYes = function () {
  console.log('yes!');
};

// named function
// better debugging in debugger's stack traces
// recursions
const printNo = function print() {
  console.log('no!');
};
randomQuiz('wrong', printYes, printNo);
randomQuiz('love you', printYes, printNo);

// Arrow function
// always anonymous
// const simplePrint = function () {
//   console.log('simplePrint!');
// };

const simplePrint = () => console.log('simplePrint!');
const add = (a, b) => a + b;
const simpleMultiply = (a, b) => {
  // do something more
  return a * b;
};

// IIFE: Immediately Invoked Function Expression
(function hello() {
  console.log('IIFE');
})();


// function calculate(command, a, b)
// command: add, substract, divide, multiply, remainder

function calculate(command, a, b) {
  switch (command) {
    case 'add':
      return a + b;
    case 'substract':
      return a - b;
    case 'divide':
      return a / b;
    case 'multiply':
      return a * b;
    case 'remainder':
      return a % b;
    default:
      throw Error('unknown command');
  }
}
console.log(calculate('add', 2, 3));

 

 

 

 

반응형