javascript

22. Function 심화학습

으누아빠 2020. 7. 7. 05:59
반응형

Function 심화

  • 출처: https://www.youtube.com/watch?v=e_lU39U-5bQ [드림코딩 by 엘리]
  • Function (함수)
  • fundamental building block in the program 프로그램의 기본 구성 요소
  • subprogram can be used multiple times 재활용이 가능함
  • performs a task or calculates a value 작업을 수행하거나 값을 계산

1. Function declaration 함수 선언

  • function name(param1, param2) { body... return;}
  • one function === one thing 하나의 함수는 하나의 일만
  • naming:doSomething, command, verb 네이밍은 동사형태
  • e.g. createCardAndPoint -> createCard, createCardAndPoint
  • function is object in JS 함수는 javascript 에서 object 이다.
function printHello() {
    console.log('Hello');
}
printHello(); //결과값 Hello

function log(message) {
    console.log(message);
}
log('Hello@'); //결과값 Hello@

2.Parameters 인수

  • premitive parameters: passed by value 기본 파라미터 : 값으로 전달
  • object parameters: passed by reference object 파라미터 : 참조로 전달
  • 즉, 참조로 전달하기 때문에 object의 값을 변경할 수 있다.
function changeName(obj) {
    obj.name = 'coder';
}

const ellie = {name:'ellie'};
changeName(ellie);

console.log(ellie); //결과값 { name: 'coder' }

3. Default parameters (added in ES6) 파라미터에 기본값 지정

  • 기본
function showMessage(message, from) {  
// 백틱을 이용하는 방법(`) [IE 에서는 지원하지 않음] console.log(`${message} by ${from}\`);  
//console.log(message + ' by ' + from);  
}  
showMessage('HI!'); //결과값: HI! by undefiend

function showMessage(message, from) {  
if(from === undefiend) {  
from = 'unknown';  
}  
console.log(`${message} by ${from}`);  
}  
showMessage('HI!') //결과값: HI! by unknown
  • ES6에서는 파라미터에 defualt 값을 지정할 수 있음
function showMessage(message, from = 'unknown') {
  console.log(`${message} by ${from}`);
}

showMessage('HI!'); //결과값 HI! by unknown

4. Rest parameters ES6에서 추가됨

  • 정해지지 않은 인수들을 배열로 받음
function myFun(a, b, ...manyMoreArgs) {
  console.log("a", a);
  console.log("b", b);
  console.log("manyMoreArgs", manyMoreArgs);
}

myFun("one", "two", "three", "four", "five", "six");

// 결과값
// a, one
// b, two
// manyMoreArgs, [three, four, five, six]

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

printAll('dream', 'coding', 'ellie');
//결과값
// dream
// coding
// ellie

5. Local scope

  • 밖에서는 안이 보이지 않고 안에서만 밖을 볼 수 있다.
let globalMessage = 'global'; // global variable

function printMessage() {
    let message = 'hello'
    console.log(message); //local variable
    console.log(globalMessage);
}

//console.log(message); //결과값 message is not defined

printMessage();
//결과값
// hello
// global

6. Return a value 값의 리턴

function sum(a, b) {
    return a + b;
}
const result = sum(1, 2);

console.log(result);
console.log(`sum: ${sum(1,2)}`);

7. Early return, Early exit (함수 제작의 좋은 방법 빨리 리턴 시키고 빨리 exit 시켜라)

// 나쁜예
function upgradeUser(user) {
    //if 문안에서 코드를 많이 작성하면 가독성이 떨어짐
    if(user.point > 10) {
        //long upgrade logic ...
    }
}

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

8. 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 다른 함수의 리턴값으로 사용이 가능

함수 선언

  • 구문 function name(param1, param2) { body... return;}
  • 함수 선언은 일반적인 함수의 형태로 script 가 실행될때 자동으로 스크립트의 맨 위 로 이동을 하여 실행하게 된다.(hoisting된다.)

함수 표현식

  • var myFunction = function name(param1, param2) { statements };
  • var myFunction = function (param1, param2) { statements };
  • 함수 표현식 (function expression)은 hoisting되지 않기 때문에 함수표현식이 정의되기 전에는 사용할수 없음
const print = function(){
    console.log('print');
}

print(); //결과값 print

const printAgain = print;
printAgain(); //결과값 print

const sumAgain = sum;
console.log(sumAgain(3, 4)); //결과값 7

9. IIFE: Immediately Invoked Function expression 함수 표현식의 즉시 호출

  • 함수를 선언함과 동시에 실행
(function() {
    console.log('IIFE');
})();