Skip to main content

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

javascript
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); // 30

The default value is used only if the property is absent or equal to undefined, but it does not apply for null.

javascript
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

javascript
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.

javascript
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); // 10000

4. Default values in functions

A very common use is destructuring function arguments.

Example:

javascript
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:3000

The = {} 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:

javascript
const user = { name: 'Alex' }; const { name: userName, age: userAge = 25 } = user; console.log(userName); // Alex console.log(userAge); // 25

6. Default + the rest operator

javascript
const user = { name: 'Alex' }; const { age = 18, ...rest } = user; console.log(age); // 18 console.log(rest); // { name: 'Alex' }

Important to remember

SituationWhat happens
The property is missingThe default value is used
The property is undefinedThe default value is used
The property is nullThe default is not used (null is not undefined)
The property is present (any value)The default value is ignored

Summary

Destructuring typeExampleResult
Objectconst { a = 1 } = {};a = 1
Arrayconst [x = 5] = [];x = 5
Nested objectconst { user: { name = 'Anon' } = {} } = {};name = 'Anon'
Functionfunction f({ a = 1 } = {}) {}Safe when the argument is missing

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.