How do you assign default values while destructuring?
Short answer
Add = defaultValue after the variable name; the default is used only when the corresponding value is undefined (not null or any other falsy value).
Advertisement
AModel answer
Add = defaultValue after the variable name; the default is used only when the corresponding value is undefined (not null or any other falsy value).
function greet({ name = 'Guest' } = {}) {
console.log(`Hello, ${name}`);
}
greet(); // 'Hello, Guest'Real-world example
Providing sensible fallback values for optional configuration object properties.
Likely follow-ups
- Why does { name = 'Guest' } need = {} as well to avoid an error when called with no arguments?
Related topics