Technical skill practice
JavaScript Optional Chaining: Safe Reads and Its Limits
Optional chaining stops a property or call chain at a nullish receiver and produces undefined. It does not make every value safe for every later operation. Keep the continuous chain and the expected shape in view.
The task
Read a missing contact’s city, compare a continuous chain with a grouped expression and test a present property that is not callable.
Runnable Node 22 example
const assert = require('node:assert/strict');
const profile = {contact: null};
assert.equal(profile.contact?.address?.city, undefined);
assert.throws(() => (profile.contact?.address).city, TypeError);
const tools = {format: 7};
assert.throws(() => tools.format?.(), TypeError);
assert.equal(tools.missing?.(), undefined);
const ready = {contact: {address: {city: 'Leeds'}}};
assert.equal(ready.contact?.address?.city, 'Leeds');
console.log(String(profile.contact?.address?.city) + ' / ' + ready.contact?.address?.city);
Expected output and explanation
The continuous chain returns undefined when contact is null. Grouping the partial result ends that protected chain; the following .city then tries to read from undefined and throws. The asserted error makes the limit explicit.
The optional call on format also throws because seven is present but not a function. The missing method short-circuits instead. Optional means the nullish value may be absent; it is not a substitute for checking a present value’s type.
Output from the example
undefined / Leeds
Pitfall to check
Optional chaining can conceal a missing required relationship if used everywhere without a data contract. Decide which fields are optional, and report invalid required data rather than silently displaying undefined. It also does not make an undeclared root identifier resolvable.
Questions, answered
Does optional chaining replace null with a default?
It returns undefined for the stopped chain. Use a separate fallback only when the application defines an appropriate replacement.
Sources and examples
ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.
Your experience. A complete resume.
Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.
Free account required. Free-plan PDF exports include a watermark.