자바스크립트의 함수는 함수 정의에 사용된 함수 매개변수의 개수와는 상관없이 몇 개의 매개변수든 전달할 수 있도록 허용한다. 이러한 특징으로 인해, 함수에 매개변수가 제공되지 않을 때 기본값을 추가함으로써, 다양한 개수의 매개변수를 처리하도록 할 수 있다.
function 내에서 매개변수의 값을 변경하면, arguments 객체가 갱신된다.
function mixArgs(first, second) {
console.log(first === arguments[0]); // true
console.log(second === arguments[1]); // true
first = "abc";
second = "def";
console.log(first === arguments[0]); // true
console.log(second === arguments[1]); // true
}
mixArgs("1", "2");
strict mode에서는 arguments 객체는 매개변수의 변경을 반영하지 않는다.
function mixArgs(first, second) {
"use strict";
console.log(first === arguments[0]); // true
console.log(second === arguments[1]); // true
first = "abc";
second = "def";
console.log(first === arguments[0]); // false
console.log(second === arguments[1]); // false
}
mixArgs("1", "2");
매개변수 기본값을 사용하는 함수의 arguments객체는 mode와 상관없이 strict mode에서의 arguments객체는 동일하게 동작한다. 또한, arguments 객체는 매개변수 기본값에 대해서 전혀 알지 못한다. 따라서 arguments 객체는 항상 초기 호출 상태를 반영한다.
function mixArgs(first, second = "second") {
console.log(arguments.length); // 1
console.log(first === arguments[0]); // true
console.log(second === arguments[1]); // false
first = "abc";
second = "def";
console.log(first === arguments[0]); // false
console.log(second === arguments[1]); // false
}
mixArgs("1");
매개변수 기본값으로는 원시 값으로 한정되지 않으며, 어떠한 표현식이든 올 수 있다. 따라서 함수를 실행시켜 반환된 값을 매개변수 기본값으로도 줄 수 있다.
function getValue() {
return 5;
}
function add(first, second = getValue()) {
return first + second;
}
console.log(add(1, 1)); // 2
console.log(add(1)); // 6
second
가 주어지지 않은 경우에만 올바른 기본값을 얻기 위해 getValue()가 호출된다. 즉, JS engine에 의해 함수 선언이 처음 해석될 때가 아니라 두 번째 인자 없이 add()를 호출할 때만 getValue()가 호출된다.
또한 나중에 선언된 매개변수의 기본값으로 앞에서 선언한 매개변수를 사용할 수도 있다.
function add(first, second = first) {
return first + second;
}
console.log(add(1, 1)); // 2
console.log(add(1)); // 2
하지만, 다른 매개변수를 참조할 경우에는 그 인자보다 먼저 정의된 인자만 참조 가능하다. 왜 그럴까?
=> TDZ에서의 매개변수 기본값