JS 기초 강의(ES5+) - # Function expression (5)

Minsoo·2021년 8월 12일
0

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');
    };
    print();
    const printAgain = print;
    printAgain();
    const sumAgain = sum;
    console.log(sumAgain(1, 3));

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');
    })();

3. 계산기 함수 만들기

  • function calculate(command, a, b)
    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)); // -> [5]

0개의 댓글

관련 채용 정보