How to Use Default Values in Destructuring in JavaScript
In JavaScript, you can assign
default values during destructuring by using the syntax { property = defaultValue } for objects or [element = defaultValue] for arrays. This ensures that if the property or element is undefined, the default value is used instead.Syntax
When destructuring, you can assign default values to variables by using the = sign after the variable name. This works for both objects and arrays.
- Object destructuring:
const { prop = defaultValue } = object; - Array destructuring:
const [element = defaultValue] = array;
If the property or element is undefined, the default value will be assigned instead.
javascript
const { name = 'Guest' } = {}; const [first = 10] = []; console.log(name); // Guest console.log(first); // 10
Output
Guest
10
Example
This example shows how to use default values when destructuring an object and an array. If the original data is missing or has undefined values, the defaults are used.
javascript
const user = { age: 25 }; const { name = 'Anonymous', age = 18 } = user; const scores = [undefined, 20]; const [math = 0, science = 0] = scores; console.log(name); // Anonymous console.log(age); // 25 console.log(math); // 0 console.log(science); // 20
Output
Anonymous
25
0
20
Common Pitfalls
One common mistake is expecting default values to apply when the property exists but is null or another falsy value. Default values only apply if the property is undefined.
Also, if you try to destructure from null or undefined directly, it causes an error.
javascript
const obj = { value: null }; const { value = 100 } = obj; console.log(value); // null, not 100 // Wrong: destructuring from undefined // const { x = 1 } = undefined; // Throws TypeError // Correct: provide default empty object const { x = 1 } = undefined ?? {}; console.log(x); // 1
Output
null
1
Quick Reference
Remember these key points when using default values in destructuring:
- Defaults apply only if the value is
undefined. - Use
=after the variable name to set a default. - Destructuring from
nullorundefineddirectly causes errors. - For safe destructuring, provide a default empty object or array.
Key Takeaways
Use
= defaultValue syntax to assign default values during destructuring.Default values only apply when the original value is
undefined, not null or other falsy values.Always avoid destructuring directly from
null or undefined to prevent errors.Provide fallback empty objects or arrays when destructuring from possibly missing data.
Default values work the same way for both object and array destructuring.