Default values in destructuring
Great question - default values in destructuring are a very convenient and commonly used ES6 feature, especially in real projects (for example, in React hooks or API responses). Let's go through it step by step.
1. The general idea
If an object or array doesn't have the value you need, you can give it a default value right at the point of destructuring.
Example with an object
const user = { name: 'Alex' };
// there's no age in the object, so 30 is used
const { name, age = 30 } = user;
console.log(name); // Alex
console.log(age); // 30The default value is used only if the property is absent or equal to
undefined, but it does not apply fornull.
const obj = { a: undefined, b: null };
const { a = 1, b = 2 } = obj;
console.log(a); // 1 (undefined -> the default applies)
console.log(b); // null (null is not undefined)2. Default values in an array
const arr = [10];
const [a, b = 20, c = 30] = arr;
console.log(a); // 10
console.log(b); // 20 (default applied)
console.log(c); // 30 (default applied)3. Nested destructuring with defaults
You can specify default values at any level of nesting.
const user = {
name: 'Alex',
address: { city: 'Paris' }
};
// If address.zip is missing, use 10000
const {
address: { city, zip = 10000 }
} = user;
console.log(city); // Paris
console.log(zip); // 100004. Default values in functions
A very common use is destructuring function arguments.
Example:
function connect({ host = 'localhost', port = 3000 } = {}) {
console.log(`Connecting to ${host}:${port}`);
}
connect(); // Connecting to localhost:3000
connect({ port: 8080 }); // Connecting to localhost:8080
connect({ host: 'api.com' }); // Connecting to api.com:3000The
= {}here matters - if no argument is passed at all, there will be no error.
5. Combining with renaming
You can rename variables and give them defaults at the same time:
const user = { name: 'Alex' };
const { name: userName, age: userAge = 25 } = user;
console.log(userName); // Alex
console.log(userAge); // 256. Default + the rest operator
const user = { name: 'Alex' };
const { age = 18, ...rest } = user;
console.log(age); // 18
console.log(rest); // { name: 'Alex' }Important to remember
| Situation | What happens |
|---|---|
| The property is missing | The default value is used |
The property is undefined | The default value is used |
The property is null | The default is not used (null is not undefined) |
| The property is present (any value) | The default value is ignored |
Summary
| Destructuring type | Example | Result |
|---|---|---|
| Object | const { a = 1 } = {}; | a = 1 |
| Array | const [x = 5] = []; | x = 5 |
| Nested object | const { user: { name = 'Anon' } = {} } = {}; | name = 'Anon' |
| Function | function f({ a = 1 } = {}) {} | Safe when the argument is missing |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.