자바스크립트 3-2: Function expression

수정·2022년 6월 11일
0

1

목록 보기
7/12
post-thumbnail

1. Function expression

  • a function declaration can be called earlier than it is definend. (hoisted)
  • a function expression is created when the execution reached it.
const print = function () { //anonymous function
    console.log('print');
};
print();
=print
const printAgain = print;
printAgain();
=print
const sumAgain = sum;
console.log(sumAgain(1,3))
=4

2. Callback funtion using function expression

function randamQuiz(answer, printYes, printNo) {
    if(answer === 'love you') {
        printYes();
    } else {
        printNo();
    }
}

anonymous function: 이름이 없는 function

const printYes = function (){
    console.log('yes!');
};

named function

  • better debugging in debugger's stack traces
  • recursions
const printNo = function print() {
    console.log('no!')
    print();
};
randamQuiz('wrong', printYes, printNo);
randamQuiz('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');
})();
=IIFE가 출력된다.

출처: 드림코딩 자바스크립트 기초 강의 (ES5+)

0개의 댓글