2 분 소요

함수

1. 정의

  • fundamental building block in the program(기본적인 빌딩 블록)
  • subprogram can be used multiple times(여러 번 재사용 가능)
  • performs a task or calculates a value(한가지 일 또는 값 계산할때 사용)
  • 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(리턴값으로도 리턴이 가능)

0

2. 함수 선언

  • function name(param1, param2) { body… return;
  • one function === one thing (하나의 함수는 한가지 일만 하도록 만들어야함)
  • naming: doSomething, command, verb (이름 지을때는 동사형으로)
    • createCardAndPoint -> createCard, createPoint(길거나 복잡할때는 세분화 하기)
  • function is object in JS
    • 자바스크립트에서 function은 object임.
    • 변수에 할당할 수있고, parameter로 전달되고, 함수를 리턴할 수있음

1

2

3

4

function showError(){
  console.log('error');
}
showError();
<--함수선언문-->
let showError = function(){
  console.log('error');
}
showError();
<--함수표현문-->
let showError = () => {
  console.log('error');
}
showError();
<--화살표함수-->

5

3. Parameters (매개변수)

  • primitive parameters: passed by value(기본 매개변수: 값으로 전달)
  • object parameters: passed by reference(객체 매개변수: 참조로 전달)

4. Default parameters

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

showMessage('Hi!');

6

* 호출할때 from값을 전달하지 않았으므로 unknwon으로 대체됨.

5. Rest parameters (…)

  • …은 배열 형태를 의미함
function printAll(...args){
  for(let i=0; i<args.length; i++){   //for문
    console.log(args[i]);
  }
  for(const arg of args){            //for of문
    console.log(arg);
  }
  args.forEach((arg)=>console.log(arg)); //forEach
}

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

7

6. local scope

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

function printMessage(){
  let message='hello';          //부모 지역변수
  console.log(message);         //본인의 지역변수를 불러옴 'hello'
  console.log(globalMessage);   //글로벌 변수를 불러옴 'global'

function printAnother(){    
  console.log(message);    //부모의 지역변수를 불러옴 = 'hello'
  console.log(globalMessage);
  let childMessage = 'hello';  // 자식 지역변수
  }
  // console.log(childMessage); //자식지역변수 불러옴 = error
}

printMessage();

8

7. Return a value

function sum(a,b){
  return a+b;
}

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

9

8. Early return, Early exit

  • 코드 지적질 받을 수있음.
function upgradeUser(user){
  if(user.point>10){
   // long upgrade logic...
  }
}
<--bad-->
functionupgradeUser(user){
  if(user.point<=10){
    return;
  }
  // long upgrade logic...
}

* 조건이 맞지 않을때는 빨리 리턴을 해서 함수를 종료하고,

조건이 맞을때만 필요한 로직들을 실행하는게 더 좋음.

(조건이 맞지않은경우, 값이 undifined , 값이 -1인 경우..)

9. Arrow fucntion

let add = function(num1, num2){
 return num1 + num2;
}

=> 를 넣는 대신, function을 없앨 수 있음.

본문이 한줄이고 retrun문이 있으면 retrun을 생략 할 수 있음

let add = (num1, num2) => {
 num1 + num2;
}

return문은 {}를 ()로 바꿀수있음

let add = (num1, num2) => (num1 + num2;)

return문이 한줄이라면 ()를 없앨 수 있음

let add = (num1, num2) => num1 + num2;

10. IIFE: Immediately Invoked Function Expression

(functionhello() {
 console.log('IIFE');
})();

* 선언한 함수를 ()로 묶고 맨뒤에 ( );하면 바로 호출 할 수 있음. 10

댓글남기기