SOOM_BLOG [숨숨 블로그]

[Javascript] Function 선언과 표현 (feat. 드림코딩 by 앨리) 본문

TIL/js

[Javascript] Function 선언과 표현 (feat. 드림코딩 by 앨리)

soomst 2022. 3. 22. 20:57

Function

  • fundamental building block in the program
  • subprogram can be used multiple times
  • performs a task or calculates a value
  1. Function declation

    • function name (param1, param1) {body ... return;}
    • one function === one thing : 함수 하나는 한 가지 일만 해야한다.
    • naming : doSomething, command, verb
    • function is object in JS
  2. Parameters

    • premitive parameters : passed by value
    • object parametser : passed by reference ☆☆
  3. Default Parameters (added in ES6)

    • parameter 옆에 default 값을 지정.
    function showMessage (message, from = 'unknown') {
        console.log(`${message} by ${from}`);
    }
  4. Rest Parameters (added in ES6)

    • parameter가 배열 형태로 전달된다.
    function printAll(...args) {
        for (const arg of args) {
            console.log(arg);
        }
    }
    
    printAll('dream', 'coding', 'ellie'); // dream coding ellie
  5. Local Scope
    ❗️ 자바스크립트에서 Scope란? 밖에서는 안이 보이지 않고 안에서만 밖을 볼 수 있다.

    let globalMessage = 'global'; //global variable
    function printMessage() {
        let message = 'hello';
        console.log(message); //local variable
        console.log(globalMessage);
    
        function printAnother() {
            console.log(message);
            let childMessage = 'hello';
        }
    
        console.log(childMessage); // error!
    }
    printMessage(); // hello global
    console.log(message); // error!
  6. Return a value : return이 정의되지 않은 함수는 'return undefined'가 default이다.

  7. Early return, early exit
    조건이 맞지 않는 경우, 값이 undefined인 경우, 값이 -1인 경우 등등 --> 빨리 return하고, 아닌 경우의 로직을 타게끔 작성하는 것이 좋음.

    // bad
    function upgradeuser(user) {
        if (user.point > 10) {
            // long upgrade logic...
        }
    }
    
    //good
    function upgradeuser2(user) {
        if (user.point <= 10) {
            return;
        }
        // long upgrade logic...
    }

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 function : 파라미터 전달이 되며
  • can be returned by another function : 리턴 값으로도 리턴이 된다.
  1. Function Expression

    • a function declaration can be called earlier than it is defined. (hoisted)
      function declaration은 함수가 선언되기 이전에 호출해도 가능하다. 자바스크립트 엔진이 선언된 것을 제일 위로 올려주기 때문이다.
    • a function expression is created when the execution reaches it.
      function expression은 할당된 다음부터 호출이 가능하다.
    print(); // error, function expression은 할당된 다음부터 호출이 가능.
    
    //function expression
    const print = funtion () { // 함수에 이름이 없는 경우 : anonymous function
        console.log('print');
    }
    
    const test = funtion testFunction() { // 함수에 이름을 지정해준 경우 : named function
        console.log('print');
    }
    
     print(); // print
     const printAgain = print; // 다른 변수에 할당 가능.
     printAgain(); // print
    
     sum(1,2); // 3, function declaration은 선언 이전에 호출 가능! (호이스팅)
    
     //function declaration
     function sum (num1, num2) {
     console.log(num1+num2);
     }
    
  2. Callback function using function expression
    함수를 전달해서 원하는 상황에 호출하게 하는 것을 Callback function이라고 한다.

    //Callback functions : printYes, printNo
    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 debuger's stack traces : 디버깅할 때 더 편함
    // - recursions : 재귀함수 가능
    const printNo = function print() {
     console.log('no!');
    }
    
    randomQuiz('wrong', printYes, printNo); // no!
    randomQuiz('love you', printYes, printNo); // yes!
  3. Arrow function : always anonymous function

    • 가독성이 더 좋다.
    • 상위 환경에서의 this를 참조한다.
    
    // Arrow function
    const simplePrint = () => console.log('simplePrint!');
    const add = (a,b) => a + b;
    const simpleMultiply = (a,b) => {
     //do something more
     return a \* b;
    }
    
  4. IIFE : Immediately Invoked Function Expression
    선언함과 동시에 함수를 바로 호출하고 싶을 때

    (function hello() {
     console.log('IIFE');
    })(); // IIFE

참고 영상

[드림코딩 by 앨리] - 자바스크립트 5. Arrow Function은 무엇인가? 함수의 선언과 표현