Reputation: 20508
I am using default parameters, with this function:
function defaultstest({ test = { done: false, test: true }, done = false } = {}) {
console.log(test, done)
}
If I call it as defaultstest()
, defaultstest({})
, or defaultstest({ done: true })
, the defaults are set correctly.
But when I add a property to the test object, the others are not set to their default.
defaultstest({ test: { done: true } }) >> { done: true } false
How can I ensure that the optional properties are set to their defaults?
Upvotes: 2
Views: 121
Reputation: 4660
You can't supply nested default arguments. In your example, if you supply test, then it is not going to be assigned to the default object you supplied with property values test and done.
Default values are only supplied if no value or undefined is passed to the function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters.
You could use Object.assign (ES6) or an extend function to accomplish this:
function defaultstest(test = {}, done = false ) {
test = Object.assign({done: false, test: true}, test);
console.log(test, done)
}
Otherwise you are going to need to flatten your arguments.
If you use babel to transpile this to ES5 code, it may become more clear:
function defaultstest() {
var _ref = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var _ref$test = _ref.test;
var test = _ref$test === undefined ? { done: false, test: true } : _ref$test;
var _ref$done = _ref.done;
var done = _ref$done === undefined ? false : _ref$done;
console.log(test, done);
}
Specifically, note the assignment to test and done:
var test = _ref$test === undefined ? { done: false, test: true } : _ref$test;
var done = _ref$done === undefined ? false : _ref$done;
Upvotes: 1
Reputation: 1072
There is no option for nested default arguments in ES6/ES2015. check out the transpiled source code code below.
function defaultstest() {
var _ref = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var _ref$test = _ref.test;
var test = _ref$test === undefined ? { done: false, test: true } : _ref$test;
var _ref$done = _ref.done;
var done = _ref$done === undefined ? false : _ref$done;
console.log(test, done);
}
Upvotes: 0