함수의 파라미터에 기본값을 설정해줄 수 있다.
// 함수를 선언하며 지정한 매개변수 (아래의 time, name)가 parameter이다.
function greeting(time, name = "wrold") {
console.log(`hello ${name}! good ${time}`);
}
// 함수 실행시 전달하는 인자(아래의 'morning', '김코딩')가 argument 이다.
greeting("morning", "김코딩"); // hello 김코딩! good morning
//아무 argument를 전달해주지 않게 되면 기본값으로 설정한 'world'가 들어간다.
greeting("morning"); // hello world! good morning
만약 기본값을 설정하지 않고, 아무 argument 도 전달해주지 않으면 undefined가 출력된다.
function greeting(name) {
console.log(`hello ${name}`);
}
greeting(); // hello undefined
기본값을 설정해주었어도, argument는 parameter에 왼쪽부터 순서대로 들어간다.
따라서 기왕이면 기본값이 설정되어 있는 parameter는 오른쪽에 쓰는 것이 좋다.
,
를 넣고 두번째 argument를 적으면 SyntaxError가 발생한다.undefined
를 넣으면 기본 값으로 리턴된다.null
을 넣으면 null
로 리턴된다.function greeting(name = 'world', time){
console.log(`hello ${name}, good ${time}`);
}
greeting('morning'); // hello morning, good undefined
greeting(, "morning"); //SyntaxError: Unexpected token ','
greeting(undefined, "morning"); // hello world, good morning
greeting(null, 'morning'); // hello null, good morning