기본 함수 매개변수(default function parameter)를 사용하면 값이 없거나 undefined가 전달될 경우 매개변수를 기본값으로 초기화할 수 있습니다.
구문
function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
statements
}
설명
JavaScript에서, 함수의 매개변수는 가 기본입니다. 그러나, 일부 상황에서는 다른 기본 값을 설정하는 것이 유용할 수 있습니다. 이게 기본 매개변수가 도움이 될 수 있습니다.undefined
과거에는, 기본값 설정을 위한 일반 전략이 함수 몸통(body)에서 매개변수 값을 검사해 undefined인 경우 값을 할당하는 것이었습니다.
다음 예제에서, 호출 내 b를 위해 아무 값도 제공되지 않은 경우, 그 값은 a*b를 평가할 때 undefined일 거고 multiply 호출은 NaN이 반환될 겁니다. 그러나, 이는 이 예제의 두 번째 줄에 걸립니다:
function multiply(a, b) {
return a * b;
}
multiply(5, 2); // 10
multiply(5); // NaN !
이를 방지하기 위해서 multiply 함수가 오직 한 개의 인수만 있다면 b를 1로 설정하는 방식을 사용하곤 했습니다.
function multiply(a, b) {
b = (typeof b !== 'undefined') ? b : 1;
return a*b;
}
multiply(5, 2); // 10
multiply(5); // 5
ES6에서 기본 매개변수라면, 함수 몸통 내 검사는 더 이상 필요치 않습니다. 이제, 간단히 함수 머리(head)에 b의 기본값으로 1을 둘 수 있습니다:
function multiply(a, b = 1) {
return a*b;
}
multiply(5, 2); // 10
multiply(5); // 5
multiply(5, undefined); // 5
예
undefined 전달
여기 두 번째 호출에서, 설사 두 번째 인수를 호출할 때 명시해서 undefined (null이 아니긴 하지만)로 설정하더라도 , color 인수의 값은 기본값입니다.
function setBackgroundColor(element, color = 'rosybrown') {
element.style.backgroundColor = color;
}
setBackgroundColor(someDiv); // 'rosybrown'으로 색 설정
setBackgroundColor(someDiv, undefined); // 'rosybrown'으로 색 설정
setBackgroundColor(someDiv, 'blue'); // 'blue'로 색 설정
호출 시 평가
기본 인수는 호출 시에 평가됩니다, 그래서 가령 Python에서와는 달리, 새로운 객체는 함수가 호출될 때마다 생성됩니다.
function append(value, array = []) {
array.push(value);
return array;
}
append(1); //[1]
append(2); //[2], [1, 2]가 아니라
이는 심지어 함수 및 변수에도 적용됩니다:
function callSomething(thing = something()) { return thing }
function something(){
return "sth";
}
callSomething(); //sth
기본 매개변수는 나중에 기본 매개변수로 이용 가능합니다
이미 마주친 매개변수는 나중에 기본 매개변수로 이용할 수 있습니다:
function singularAutoPlural(singular, plural = singular+"s",
rallyingCry = plural + " ATTACK!!!") {
return [singular, plural, rallyingCry ];
}
//["Gecko","Geckos", "Geckos ATTACK!!!"]
singularAutoPlural("Gecko");
//["Fox","Foxes", "Foxes ATTACK!!!"]
singularAutoPlural("Fox","Foxes");
//["Deer", "Deer", "Deer ... change."]
singularAutoPlural("Deer", "Deer", "Deer peaceably and respectfully
petition the government for positive change.")
이 기능은 정직한 방식으로 근사되고 많은 극단적인 경우(edge case)가 처리되는 법을 보여줍니다.
function go() {
return ":P"
}
function withDefaults(a, b = 5, c = b, d = go(), e = this,
f = arguments, g = this.value) {
return [a,b,c,d,e,f,g];
}
function withoutDefaults(a, b, c, d, e, f, g){
switch(arguments.length){
case 0:
a
case 1:
b = 5
case 2:
c = b
case 3:
d = go();
case 4:
e = this
case 5:
f = arguments
case 6:
g = this.value;
default:
}
return [a,b,c,d,e,f,g];
}
withDefaults.call({value:"=^_^="});
// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="]
withoutDefaults.call({value:"=^_^="});
// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="]
함수 몸통 내에 정의된 함수
Gecko 33 (Firefox 33 / Thunderbird 33 / SeaMonkey 2.30)에서 도입됨. 함수 몸통에 선언된 함수는 기본 매개변수 내에 참조될 수 없고 ReferenceError (현재 SpiderMonkey 에서는 TypeError, bug 1022967 참조) 가 발생합니다. 기본 매개변수는 항상 먼저 실행되고, 함수 몸통 내 함수 선언은 나중에 평가합니다.
// 작동하지 않음! ReferenceError 발생.
function f(a = go()) {
function go(){return ":P"}
}
기본 매개변수 뒤 기본값 없는 매개변수
Gecko 26 (Firefox 26 / Thunderbird 26 / SeaMonkey 2.23 / Firefox OS 1.2) 이전에, 다음 코드는 SyntaxError로 끝납니다. 이는 bug 777060에서 해결되었고 이후 버전에서 예상대로 작동합니다:
function f(x=1, y) {
return [x, y];
}
f(); // [1, undefined]
기본값 할당 있는 해체된 매개변수
기본값 할당을 해체 할당 표기에 쓸 수 있습니다:
function f([x, y] = [1, 2], {z: z} = {z: 3}) {
return x + y + z;
}
f(); // 6
스펙
브라우저 호환성
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | 49 | 15.0 (15.0) | No support | No support | No support |
| Parameters without defaults after default parameters | 49 | 26.0 (26.0) | ? | ? | ? |
| Destructured parameter with default value assignment | No support | 41.0 (41.0) | ? | ? | ? |
| Feature | Android | Android Webview | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
|---|---|---|---|---|---|---|---|
| Basic support | No support | 49 | 15.0 (15.0) | No support | No support | No support | 49 |
| Parameters without defaults after default parameters | No support | 49 | 26.0 (26.0) | ? | ? | ? | 49 |
| Destructured parameter with default value assignment | No support | ? | 41.0 (41.0) | ? | ? | ? | ? |