389 words
2 minutes

JavaScript Destructuring Defaults and null in JSON Options

2026-11-14
Frontend
JavaScript
/
Node.js
/
Troubleshooting

A JavaScript function that accepts an options object can have two layers of defaults. In function settings({ retries = 3 } = {}), the outer default handles a missing argument or undefined. The inner default handles a missing property or one whose value is undefined. A JSON response can contain null at either layer, with a different result each time. Passing null as the options object throws a TypeError. Passing { "retries": null } leaves retries set to null.

Check both layers with the same JSON inputs#

If your API treats null as missing at both layers, use ?? {} before destructuring and ?? on the fields that need defaults. The first fallback supplies an object. The field fallbacks preserve explicitly configured values such as zero retries or disabled logging.

This fixture was run on Node.js 24.13.0 on macOS arm64. Save it as settings.mjs and run node settings.mjs.

import assert from "node:assert/strict";
function rawSettings({ retries = 3, log = true } = {}) {
return { retries, log };
}
function settings(options) {
const { retries, log } = options ?? {};
return { retries: retries ?? 3, log: log ?? true };
}
const defaults = { retries: 3, log: true };
assert.deepEqual(rawSettings(), defaults);
assert.deepEqual(settings(), defaults);
const cases = [
["{}", defaults, defaults],
["null", TypeError, defaults],
['{"retries":null,"log":null}', { retries: null, log: null }, defaults],
['{"retries":0,"log":false}', { retries: 0, log: false }, { retries: 0, log: false }],
['{"retries":null,"log":false}', { retries: null, log: false }, { retries: 3, log: false }],
];
for (const [json, rawExpected, normalizedExpected] of cases) {
const options = JSON.parse(json);
if (rawExpected === TypeError) {
assert.throws(() => rawSettings(options), TypeError);
} else {
assert.deepEqual(rawSettings(options), rawExpected);
}
assert.deepEqual(settings(options), normalizedExpected);
}
console.log("All five JSON cases and both omitted-argument checks passed.");

The mixed case shows why the fallback belongs on each nullable field. A response can ask for the default retry count and disable logging in the same object. Using log || true there would discard the explicit false, just as filtering with Boolean removes valid falsy values.

Use a field fallback only where the API gives null the same meaning as an absent field. If null means “clear this setting,” keep that field’s destructuring default and let null pass through. Schema validation belongs before normalization when the API can send values outside the expected types.

References:

JavaScript Destructuring Defaults and null in JSON Options
https://laplusda.com/en/posts/javascript-destructuring-default-null/
Author
Zero
Published at
2026-11-14
License
CC BY-NC-SA 4.0