What do ?. and ?? do? Why is ?? often safer than || for default values?
Show the explanation
Model answer.
- Optional chaining `?.` stops and returns
undefinedif the value on its left isnullorundefined, instead of throwing. It works for properties, calls and indexes:user?.address?.city,callback?.(),list?.[0]. - Nullish coalescing `??` returns the right side only when the left is
nullorundefined.
The difference from ||: || falls back for any falsy value, including legitimate ones like 0, '' and false.
const settings = { volume: 0, nickname: '' };
settings.volume || 50; // 50: wrong, the user chose 0
settings.volume ?? 50; // 0: correct
settings.nickname ?? 'Guest'; // '': kept, because it was setUse ?? for defaults when 0, empty string or false are valid values. Use || only when every falsy value should really be replaced. (You cannot mix ?? with ||/&& without brackets; JavaScript forces you to be explicit.)
Original UniCircle question. Last reviewed 22 Oct 2026.
