Back to results for “Spread & Rest”
JavaScript › Destructuring, Spread & Rest

How do you assign default values while destructuring?

Intermediate

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.

Common follow-ups: Why does { name = 'Guest' } need = {} as well to avoid an error when called with no arguments?