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.

JavascriptConfig Management

Code

javascriptsnippet
17 lines
// ?? (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

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.