2.3.1 기본 매개변수
ES6 기본 매개변수 문법을 사용해 매개변수의 기본값을 간결하게 표현할 수 있다.
function looseCheck(a, b, c) {
console.log([a, b, c]);
}
looseCheck(1, 2, 3); // [1, 2, 3]
looseCheck(1, 2); // [1, 2, undefined)
looseCheck(1); // [1, undefined, undefined)function tightCheck(a, b, c) {
if (
(typeof a === 'undefined') ||
(typeof b === 'undefined') ||
(typeof c === 'undefined')
) {
throw new Error('Not all parameters are specified.');
}
console.log([a, b, c]);
}
tightCheck(1, 2, 3); // [1, 2, 3]
tightCheck(1, 2); // Error: Not all parameters are specified.
function useDefault(_a, _b, _c) {
const a = typeof _a === 'undefined' ? 1 : _a;
const b = typeof _b === 'undefined' ? 1 : _b;
const c = typeof _c === 'undefined' ? 1 : _c;
console.log([a, b, c]);
}
useDefault(1, 2, 3); // [1, 2, 3]
useDefault(1, 2); // [1, 2, 1]Last updated