Nullish Coalescing Defaults For Option Objects
Destructured options with ?? fall back only on null and undefined, so legitimate zero, empty string, and false survive where || would overwrite them.
Code
// ?? (nullish coalescing) treats only null / undefined as missing; || also swallows 0, '', and false
function connect({ host = 'localhost', port = 5432, retries = 3, label = '' } = {}) {
return { host, port, retries, label };
}
console.log('all defaults:', connect());
console.log('zeros kept :', connect({ port: 0, retries: 0 }));
console.log('label unset :', connect({ label: undefined }));
// destructuring defaults only catch undefined: null passes through as literal null, only ?? fills it in
console.log('null passes :', connect({ host: null }));
const zeroPort = { port: 0 };
console.log('|| vs ??:', zeroPort.port || 5432, '|', zeroPort.port ?? 5432);
// mixing ?? with || requires explicit parentheses; the parser rejects implicit grouping
const timeoutMs = 0;
console.log('grouped :', (timeoutMs ?? 3000) || 'fallback');Inside the snippet
Nullish Coalescing Defaults For Option Objects keeps everything in the function connect.
The result comes back as an object carrying host, port, retries.
Putting it to use
The main signature reads function connect({ host = 'localhost', port = 5432, retries = 3, label = '' } = {})
Running the file prints labeled results such as all defaults:, zeros kept :, label unset : — each operation’s effect is visible in the output.
The call returns host, port, retries — destructure what you need at the call site.
Core lines
return { host, port, retries, label };
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Does `connect` modify its input?
- No — a new value is constructed for the result and the arguments are never written to.
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit. The file defines `connect` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.