function myFunction(data, options = { merge: true, cache: false }) {
console.log({ merge: options.merge });
console.log({ cache: options.cache });
console.log("----------------------");
}
myFunction({}, { cache: true });
myFunction({}, { merge: false });
myFunction({});
How can I do, in the above example, to avoid losing the default value of the optional field "merge"?
You can use default value assignment with the destructuring assignment notation
{ merge = true, cache = false } = {}
function myFunction(data, { merge = true, cache = false } = {}) {
console.log({ merge: merge });
console.log({ cache: cache });
console.log("----------------------");
}
myFunction({}, { cache: true });
myFunction({}, { merge: false });
myFunction({});
Another way is to use the fallback values feature of destructuring
function myFunction(data, options = {}) {
const {merge = true, cache = true} = options;
console.log({merge});
console.log({cache});
console.log("----------------------");
}
One of the ways:
function myFunction(data, options) {
options = {merge: true, cache: true, ...options}
console.log({merge: options.merge});
console.log({cache: options.cache});
console.log("----------------------");
}