본문 바로가기

Frontend/자바스크립트 Java Script

[자바스크립트] function

자바스크립트에 추가된 class는 자바처럼  pure한  objec가 아님. 가짜 object-oriented

procedure language.

input(parameter)를 받아 output하는 것이 함수

 

Function

- fundamental building block in the program

- subprogram can be used multiple times

- performs a task or calculates a value

 

1. Function declaration

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

one function = one thing

naming: doSomething, command, verb

e.g. createCardAndPoint -> createCard, cratePoint

function is object in JS

변수에 할당, 파라미터로 전달, 함수에 리턴 가능

 

타입스크립트          파라미터타입,리턴타입 명시

function log(message: string): number {

    console.log(message);

    return 0;

}

 

 

2. Parameters

premitive parameters: passed by value

object parameters: passed bt reference

 

function changeName(obj) {

    obj.name = 'coder';

}

const ellie = { name: 'ellie' };

changeName(ellie);

console.log(ellie);   ->{name: "coder"}

-object는 reference로 전달되기 때문에 함수 안에서 오브젝트 값을 변경하면 그 변경된 사항이 그대로 전달됨.

 

3. Default Parameters (added in ES6)

function showMessage(message, from = 'unknown') {

    console.log(`${message} by ${from}`);

}

showMessage('Hi');   ->Hi by unknown

 

4. Rest Parameters (added in ES6)

function printAll(...args) {

    for (let i = 0; i<args.length; i++) {

        console.log(args[i]);

    }

 

    for (const arg of args) {

        console.log(arg);

    }

 

    args.forEach((arg) => console.log(arg));

}

printAll('dram', 'coding', 'ellie');

 

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. 자식은 부모메세지 볼 수 있으나 자식메세지를 상위에서 접근하면 에러

    (return undefined;    //  리턴값이 없으면 생략)

}

printMessage();

console.log(message);  ->error

 

6. Return a value

function sum(a, b) {

    return a + b;    

}

const result = sum(1, 2);

console.log(`sum: ${sum(1, 2)}`);    -> sum: 3

리턴 값이 없는 경우  return undefinded가 생략되어있음

 

7. Early return, early exit

// bad case

fuction upgraderUser(user) {

    if (user.point >10) {

        // long upgrade logic.....

    }

}

10점 이상인 경우 긴 로직을 작성해야 할 때 

조건에 맞지 않을 때는 빨리 리턴해서 함수 종료하고 긴 조건을 뒤로 작성. 가독성도 좋음.

 

// good case

function upgradeUser(user) {

     if (user.point <= 10) {

        return;

    }

    // long upgrade logic....

}

 

 

Functino 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 returned by another function

 

1. Function Expression

a function declaration can be called earlier than than is is defined. (hoiseted)

a function expression is created when the execution reaches it.

 

위 6번의 sum함수같은 function declaration은 선언하기 전에도 호출가능함(호이스팅)
print();    // function expression(아래처럼 변수에 선언)는 할당된 다음부터 호출가능. 선언하기 전 호출하면 에러남.

const print = function () {       // anonymous function

    console.log('print');

};

print();

const printAgin = print;

printAgain();

const sumAgin = sum; 

console.log(sumAgain(1, 2));

 

 

2. Callback function using function expression

함수를 파라미터로 전달(printYes, printNo)해서 상황에 맞게 그 함수를 호출하는 것을 callback함수라고 한다.

 

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 -better debugging in debugger's stack trace

                                                                recursions반복,되풀이. 함수 안에서 함수 자신을 부르는 것

    console.log('no!');

}

 

randomQuiz('wrong', printYes, printNo);      ->No

randomQuiz('love you', printYes, printNo);   ->Yes

 

 

 

Arrow Function

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

 

const add = function (a, b) {

    return a + b;

};

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

const simpleMultiply = (a, b) => {

    return a * b;              // block을 쓰려면 return도 써줘야함

}

 

 

IIFE: Immediately Invoked Function Expression

함수를 선언하고 후에 호출하는 것이 아니라

선언함과 동시에 바로 호출하려면 괄호로 묶어 호출. 요즘은 잘 사용하지 않음.

( function hello() {

    console.log('IIFE');

})();