Skip to content
Back to all posts
Technology

JavaScript Destructuring Defaults: Avoid Undefined and Subtle Bugs

Use default values in object and array destructuring correctly, including nested options, null behavior, and function parameters.

2 min read

TechSilo

Technology writer & developer

Destructuring makes it easy to extract values from objects and arrays. Adding a default prevents many unnecessary checks—but the default is applied only when the extracted value is undefined.

Object defaults

javascript
const settings = { theme: 'dark' };

const { theme, pageSize = 20 } = settings;
console.log(theme);    // dark
console.log(pageSize); // 20

A missing property evaluates to undefined, so the default is used.

Defaults do not replace null

javascript
const config = { retries: null };
const { retries = 3 } = config;
console.log(retries); // null

If both null and undefined should trigger a fallback, use nullish coalescing:

javascript
const retryCount = retries ?? 3; // 3

Avoid retries || 3 when values like 0 are legitimate.

Default values for function options

javascript
function createRequest({ timeout = 5000, retries = 0 } = {}) {
  return { timeout, retries };
}

console.log(createRequest());                // { timeout: 5000, retries: 0 }
console.log(createRequest({ timeout: 8000 })); // { timeout: 8000, retries: 0 }

The second default, = {}, is important: without it, calling createRequest() would try to destructure undefined and throw.

Nested destructuring

javascript
const options = { ui: { compact: true } };
const {
  ui: { compact = false, accent = 'blue' } = {},
} = options;

console.log(compact, accent); // true blue

If options.ui is explicitly null, the pattern above still throws. Normalize the input first if null is possible:

javascript
const ui = options.ui ?? {};
const { compact: isCompact = false } = ui;

Array defaults

javascript
const [first = 'guest', second = 'viewer'] = ['Ada'];
console.log(first, second); // Ada viewer

Destructuring defaults also work for skipped array positions: const [, second = 2] = [1].

Common mistakes

- Destructuring from null or undefined without a safe fallback.

- Expecting = value to replace null, false, or 0.

- Using deeply nested patterns when a readable ?. and ?? expression is easier.

- Reusing property names accidentally instead of renaming them: const { id: userId } = user.

Destructuring defaults are best for known, optional fields. They are not input validation: an unexpected string or object shape still needs explicit checking. If you're reviewing unfamiliar destructuring code, the [AI Code Explainer](/tools/ai-code-explainer) can help trace it.

Want to put this into practice?

Explore TechSilo's free developer tools for practical utilities you can use directly in your browser.

Related blog posts