4. JS basic (function expression - Callback, Arrow, IIFE)

Changmok LEE·2023년 1월 14일

first-class-function

functions are treated like any other variables

  • 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

  • function declaration

    • a function declaration can be called earlier than it is defined (hoisted == js엔진이 함수 선언부분를 가장 위로 올려줌)
      (함수가 선언 되기 이전에 호출해도 호출 가능 -> hoisted 되기 때문)
  • function expression

    • a function expression is created when the execution reaches it
      (변수에 함수가 할당(선언) 된 다음부터 함수 호출이 가능)
    sum(2, 3); // 호출 가능(function declaration)
    function sum(a, b) {
        return a + b;
    }
    print(); // 호출 불가능(function expression)
    const print = function () { // anonymous function
        console.log('print');
    };
    
    print();
    const printAgain = print;
    printAgain();
    
    const sumAgain = sum;
    console.log(sumAgain(1, 2));
    
  • Callback function(using function expression)

    파라미터에 함수를 전달해서 필요하면 전달된 함수를 부르도록 하는 것
    (callback)

    function randomQuiz(answer, printYes, printNo) {
    	if (answer === 'love you') {
        printYes();
      } else {
        printNo();
      }    
    }
    // anonymous function
    const printYes = function () {
    	console.log('yes!');
    };
    // named function
    // better debuging in debugger's stack trace
    // recursions
    const printNo() = function print() {
    	console.log('No!');
    	print() // recursions
    };
    randomQuiz('wrong', printYse, printNo);
    randomQuiz('love you', printYse, printNo);
  • Arrow function

    always anonymous function

    // 기본
    const simplePrint = function () {
    	console.log('simplePrint!');
    };
    // Arrow function
    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(함수 즉시 호출)

    Immediately Invoked Function Expression
    ex: (() => ())();

    (function hello() {
    	console.log('IIFE');
    })();
    
profile
이창목

0개의 댓글