Default values
Learn to give default values for missing properties in destructuring.
Default values
Sometimes a property is missing and you do not want the variable to be undefined. In destructuring you write a default value after an equals sign: const { theme = "light" } = settings.
If settings.theme exists, the variable takes that value. If it is missing or undefined, the variable becomes "light". This matches the default-value logic of function parameters.
undefined vs null
A default value only triggers for undefined. If the property is null, the default is not used; the variable stays null. This matters: null means an intentional "empty value", while undefined means "no value".
So const { count = 5 } = { count: null } gives null, not 5. Keep this in mind when testing.
Exercise Safely extract settings
Create a settings object with a retries property but no theme property. Use destructuring to pull theme with a default of "light", and retries with a default of 3. Then log each one separately with console.log.
Show example solution
const settings = { retries: 5 };
const { theme = "light", retries = 3 } = settings;
console.log(theme);
console.log(retries);
Test yourself
-
In `const { x = 5 } = { x: undefined }`, what is `x`?
- undefined
- 5
- null
- It throws an error
Show answer
5 — Correct. The `undefined` value triggers the default, so `x` becomes 5.
-
Complete the default value
const config = { }; const { timeout = ____ } = config; console.log(timeout);Show answer
const config = { }; const { timeout = 3000 } = config; console.log(timeout); -
Which assigns a default of `"dark"` to `theme`?
- `const { theme } = settings || "dark"`
- `const { theme: "dark" } = settings`
- `const [ theme = "dark" ] = settings`
- `const { theme = "dark" } = settings`
Show answer
`const { theme = "dark" } = settings` — Correct. The equals sign gives a default value inside the object pattern.
-
Match the concepts
- default value
- Triggers only for undefined
- null
- Does not trigger the default
- equals sign
- Assigns the default