참고 사이트
🔮 Destructured parameter with default value assignment
- 함수를 호출 할 때, 인자를 주지 않으면 기본 값으로 설정
function preFilledArray([x = 1, y = 2] = []) {
return x + y;
}
preFilledArray(); // 3
preFilledArray([]); // 3
preFilledArray([2]); // 4
preFilledArray([2, 3]); // 5
// Works the same for objects:
function preFilledObject({ z = 3 } = {}) {
return z;
}
preFilledObject(); // 3
preFilledObject({}); // 3
preFilledObject({ z: 2 }); // 2
function preFilledObject({ id = 1, ...rest } = {}) {
return {
id: id,
name: 'apple',
...rest,
};
}
console.log(preFilledObject());
console.log(preFilledObject({ id: 2 }));
console.log(preFilledObject({ id: 3, state: 'good' }));
function preFilledObject({ id, ...rest } = {}) {
return {
id: id,
name: 'apple',
...rest,
};
}
console.log(preFilledObject());
console.log(preFilledObject({ id: 2 }));
console.log(preFilledObject({ id: 3, state: 'good' }));
- TypeError: 인자를 주지 않고, 파라미터 기본 값을 설정하지 않은 함수 호출
function preFilledObject({ id, ...rest }) {
return {
id: id,
name: 'apple',
...rest,
};
}
console.log(preFilledObject({ id: 2 }));
console.log(preFilledObject()); // Error!