본문 바로가기
JAVASCRIPT

자바스크립트 기초 #5 | Function / Arrow function

by 승행 2021. 3. 13.

Function / Arrow function

 

 

Function

- 프로그램의 기본 구성 요소, 블록

- 재사용 가능

- 작업을 수행하거나 값 계산

 

1. Function declaration 함수 선언

- function name (param1, param2) {body ... return;}

- one function === one thing

- naming: doSomething, command, verb

  e.g. createCardAndPoint -> createCard, createPoint

- js에서 함수는 객체

function printHello(){

    console.log('Hello');

}

printHello();



function log(message){

    console.log(message);

}

log('Hello@');

log(1234);

 

 

2. Parameters

- premitive parameters: passed by value

- object parameters: passed by reference

function changeName(obj){

    obj.name = 'coder';

}

const sh ={name: 'sh'};

changeName(sh);

console.log(sh);

// sh의 이름이 coder로 변경

// object는 레퍼런스에 저장됨

 


3. Default parameters (ES6 추가)

- param 의 default 값 지정 가능

- 원래 전달되지 않은 값은 undefined

function showMessage(message, from = 'unknown'){
    console.log(`${message} by ${from}`);
}
showMessage('hi!');

 

 

4. Rest parameters (added in ES6)

- 파라미터 값 지정 시 ...을 작성하면 배열 형태로 저장

function printAll(...args){
    // 방법 1) for
    for (let i = 0; i < args.length; i++){
        console.log(args[i]);
    }

    // 방법 2) for
    for (const arg of args){
        console.log(arg);
    }

    // 방법 3) forEach
    args.forEach((arg) => console.log(arg));
}
printAll('kim', 'seung', 'hang');

 

 

5. Local 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();

 

 

6. Return a value

- return type이 없는 경우는 

- return undefined; 가 생략되어 있는 것과 같다.

function sum(a, b){
    return a + b;
}
const result = sum(1, 2);
console.log(`sum: ${sum(1,2)}`);

 

 

7. Early return, early exit

// 조건이 맞지 않는 경우 함수를 빨리 종료하고

// 조건이 맞는 경우 로직을 실행하는 것이 좋은 함수이다

 

- bad

function upgradeUser(user){
    if(user.point > 10){
        // long upgrade logic...
    }
}

 

- good

function upgradeUser(user){
    if(user.point <= 10){
        return;
    }
    // long upgrade logic...
}

 

 

8. First-class function

- js에서의 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라는 변수에 할당

// function에 아무 이름이 없고 function이라는 키워드만 이용

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!');
    // print(); // *
}

randomQuiz('love you', printYes, printNo);
randomQuiz('wrong', printYes, printNo);

callback function

- 의도적으로 특정 함수를 작성하여 호출하는 것이 아니라, 작성해놓은 함수가 어떤 이벤트 혹은 특정 시점에 도달했을 경우 시스템에서 호출하는 함수

 

 

9. Arrow function

- 함수를 간결하게 만들어 줌

- always anonymaous 항상 함수명이 없음

 

기존 방법 1)

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

 

arrow function 1)

const simplePrint = () => console.log('simplePrint!');

- function 키워드 필요 없음

- 한 줄로 작성할 경우 블럭 {} 필요 없음

- => 추가 후 한 줄로 이어주기만 하면 됨

 

기존방법 2)

const add = function (a, b) {
    return a + b;
}

 

arrow function 2)

const add = (a, b) => a + b;

 

+++ 여러줄인 경우

- 한 줄인 경우  return을 사용하지 않아도 되지만

- 여러 줄인 경우 return을 꼭 사용하여 반환해야 함

const simpleMultiply = (a, b) => {
    // do something more
    return a * b;
};

 

 

10. IIFF (Immediately Invoked Function Expression

- 함수를 선언함과 동시에 호출하는 방법

- 함수를 ()로 묶어서 작성하고 호출하듯이 (); 추가

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

 

 

 


<TEST>

 

- function calculate (command, a, b)

- command : add, substract, divide, multiply, remainder

 

 

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;
    }
}

console.log(calculate('remainder', 100, 10));