본문 바로가기

[자기계발]/유튜브로 코딩배우기

[드림코딩 엘리] 자바스크립트 Function Expression이란?

반응형

저번 글에서는 Function declaration을 알아보았다. 이번에는 Function Expression에 대해 알아보자


출처: https://dmitripavlutin.com/javascript-function-expressions-and-declarations/

1. Function Expression

/ 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 reteurend by another function

// 1. Function Expression
// a function declaration can be called ealier than it is defiend. (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; // sum 이라는 function을 다시 여기에 할당하게 되면 동일하게 호출이 가능하다.
console.log(sumAgain(1, 3));

2. Callback hell 

// 2. Callback function using function expression
// 정답 / 정답이 맞을 때의 호출 / 아닐 시의 호출 
// 이렇게 함수를 전달해서 상황에 따라 전달될 함수를 불러라고 전달하는 것을 'callback function'라고 한다.
// 2가지의 callback functions가 parameter로 전달된다.
// 이 함수의 구현상을 보면 정답이 love you 인 경우에만 printYes 라는 callback 함수를 호출하게 된다.
// viceversa
function randomQuiz(answer, printYes, printNo) {
    if(answer === 'love you') {
        printYes();
    } else {
        printNo();
    }
}
const printYes = function () { // anonymous function가 쓰였다. 
    console.log('yes!');
};

const printNo = function print() { // named function 이 사용되었다. 장점은 밑에 나열
    console.log('no!');
};
// better debugging in debugger's stack traces
// recursions = 재귀 = 자신을 정의할 때 자신을 재참조하는 방법

randomQuiz('wrong', printYes, printNo); // 결과 no!
randomQuiz('love you', printYes, printNo); // 결과 yes!

3. Arrow function

  • 함수를 간결하게 만들 수 있게 해준다. 
  • 항상 이름이 없는 anonymous function 이다.
  • Function Expression를 쓰게 되면 function 이라는 키워드도 써야하고 블록도 계속 써야되는 번거로움이 있는데
    arrow function은 function 키워드와 블록이 필요가 없다. 그냥 한 줄에 묶어서 표기하면 끝이다.
  • parameter는 a 하고 b 숫자를 받아서 return 값은 a + b ;
  • 함수형 프로그래밍 배열이나 리스트 볼 때 좋다.
  • 함수 안에서 조금 더 다양한 일들을 해야 되서 블록을 필요하다면 이런식으로 블록을 넣어서 처리할 수도 있다.
  • 대신 블록을 쓰면 return이라는 키워드를 써야한다.
// 3. 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 키워드를 써야한다.
    return a * b;
};

4. IIFE - Immediately Invoked Function Expression

선언함과 동시에 바로 호출하려면 이렇게 함수의 선언을 ( ) 로 묶은 다음 함수를 호출 하듯이 (); 를해주면 된다.

그러면 바로 함수가 호출된다. 자바스크립트에서 함수를 바로 실행하고 싶을 때 유용하게 쓸 수 있다.

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

5. QUIZ

// Fun quiz time😊
// function calculate(command, a , b)
// command: add, substract, divide, multiply, remainder

function add() {
    let a = 4;
    let b = 5;
    return a + b;
}
console.log(a+b);

function add() {
    let a = 10;
    let b = 5;
    return a - b;
}
console.log(a-b);


function add() {
    let a = 10;
    let b = 5;
    return a / b;
}
console.log(a/b);

function add() {
    let a = 10;
    let b = 5;
    return a + b;
}
console.log(a+b);

function add() {
    let a = 10;
    let b = 5;
    return a / b;
}
console.log(a/b);

function add() {
    let a = 10;
    let b = 5;
    return a % b;
}
console.log(a%b);

이렇게 보다는 

function calculate(command, a , b){
    switch(command) {
        case 'add':
            console.log(a+b);
        case 'substact':
            console.log(a-b);
        case 'divide': 
            console.log(a/b);
        case 'multiply':
            console.log(a*b);
        case 'remainder':
            console.log(a%b);
        default:
            throw Error('unknown command'); // 정해진 command가 아닐 경우 이렇게 Error를 던진다. 
            // if문을 쓰기보다 정해진 데이터를 처리하는 경우에는 switch 문을 이용해서 만드는 것이 더 좋다.
    }
}
console.log(calculate('add', 2, 3));
반응형