[JS] Javascript #4 Summary

3 minute read

Javascript #4 Summary


function

  • fundamental building block in the program

  • subprogram can be used multiple times
    • function 은 sub-program 이라고도 불린다.
  • performs a task or calculates a value



function declaration

function name(param1, param2) { body... return; }
  • function 은 JS 에서 object 이다. (--> first-class function)

  • 변수이름은 명사로, 함수이름은 do something (동사) 형태로 지정한다.

  • 하나의 함수는 한개의 일만 수행 (one function === one thing)

  • 함수이름을 정하기가 쉽지 않다면 혹시 함수내에서 너무 많은 것들을 하고 있지 않은지 고민이 필요

    • createCardAndPoint --> createCard, createPoint
function log(message) {
    console.log(message);
}
log('Hello');



parameters

  • primitive parameters: passed by value

  • object parameters; passed by reference

function changeName(obj) {
    obj.name = 'coder';
}
const bruce = { name: 'bruce' }
changeName(bruce);
console.log(bruce);

>>> {name : 'bruce'}



Default Parameters (Added in ES6)

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

>>> Hi! by unknown

===> (위의 코드를 ES6 부터는 아래와 같이 작성 가능해졌다.)

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

>>> Hi! by unknown



Rest Parameters (Added in ES6)

function printAll(...args) {
    for (let i=0; i < args.length; i++) {
        console.log(args[i]);
    }
}
printAll('Hi', 'Hello', 'bruce');

>>> Hi
>>> Hello
>>> bruce


배열은 for loop 의 of 를 통해서 아래와 같이 더 간단하게 작성 가능

function printAll(...args) {
    for (const arg of args) {
        console.log(arg);
    }
}
printAll('Hi', 'Hello', 'bruce');

>>> Hi
>>> Hello
>>> bruce

const args = ['Hi', 'Hello', 'bruce'];
args.forEach((arg) => console.log(arg));

>>> Hi
>>> Hello
>>> bruce



Scope

  • 밖에서는 안이 보이지 않고, 안에서만 밖을 볼 수 있다.



Early return, early exit

// bad case
function upgradeuser(user) {
    if (user.point > 10) {
        // long upgrade logic
    }
}
  • block 내부에 Logic 을 많이 작성하면 가독성 떨어짐
    따라서 if 와 else 를 번갈아 가면서 쓰기보다는 early return (early exit) 을 활용
// good case
function upgradeuser(user) {
    if (user.point <= 10) {
        return;  // early return
    }
    // log upgrade logic
}



First-class function

  • functions are treated like any other variable

  • can be assigned as a value to variable

  • can be passed as a an argument to other functions

  • can be returned by another function

위의 것들을 가능하게 해주는 것이 Function expression 이다.


Function Expression

  • a function declaration can be called earlier than it is defined. (hoisted)

  • a function expression is created when the execution reaches it.

const print = function () {  // anonoymous function
    console.log('print');
}
print();
const printAgain = print;
printAgain();

>>> print
>>> print



Callback function using function expression

  • 아래 코드에서 printYes, printNo 함수를 callback function 이라고 부른다.
function randomQuiz(answer, printYes, printNo) {
    if (answer == 'love you') {
        printYes();
    } else {
        printNo();
    }
}

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

// named function
// 1. better debugging in debugger's stack traces.
// 2. for use recursions.
const printNo = function print() {
    console.log('no!');
}

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

>>> no!
>>> yes!



Arrow Function

  • Always anonymous
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');
}

위의 함수를 괄호로 감싼 뒤 바로 call 하는 형태

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



Quiz

  • 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;
        default:
            throw Error('unknown command');
    }
}
console.log(calculate('add', 2, 3));

>>> 5

Leave a comment