ES6+ Modern JavaScript

Optional Chaining & Nullish Coalescing

?. safely navigates potentially null/undefined objects, while?? provides smart fallbacks that respect valid falsy values like 0, false, and ''.

What does ?. do in JavaScript?

Optional chaining ?. stops and returns undefined if the value before it is null or undefined, instead of throwing an error. user?.address?.city safely reads deeply nested data. Pair it with the nullish coalescing operator ?? to supply a fallback: user?.name ?? "Guest".

const city = user?.address?.city;          // undefined if any part is missing
const first = list?.[0];                   // arrays
callback?.();                              // call only if defined
const name = user?.name ?? "Guest";        // fallback for null/undefined
const count = settings.count ?? 10;        // keeps 0

Optional Chaining Syntax

obj?.propProperty access
obj?.method?.()Method call
arr?.[index]Array/bracket access
a?.b?.c?.dDeep chaining — stops at first null
fn?.(arg)Call function only if it exists

?? vs || Comparison

Expression|| result?? result
0 op 'default''default'0
'' op 'default''default'''
false op 'x''x'false
null op 'x''x''x'
undefined op 'x''x''x'
NaN op 'x''x'NaN

When to Use Each

?.

Accessing properties of API responses that might be null

response?.data?.user?.name
??

Default values for config options that may be 0 or false

config?.timeout ?? 5000
||

Default values where you want ANY falsy value to trigger fallback

title || 'Untitled'
??=

Initialize a variable only if it's currently null/undefined

cache ??= {}; cache[key] ??= [];

Common Pitfalls

Using || for numeric defaults — treats 0 as falsy
Use ?? for numeric/boolean defaults: port ?? 3000 (0 stays 0)
Optional chaining on the left side of assignment: obj?.prop = value
Optional chaining is read-only; you cannot assign through ?
Overusing ?. — hiding bugs where null shouldn't happen
Use ?. only where null is expected, not to silence all TypeError crashes
Cannot mix ?? and || or && without parentheses
Add explicit parentheses: (a ?? b) || c — required by the spec

Interactive Examples

Code Editor

<pre id="out"></pre>

Preview

Optional chaining and nullish coalescing — step by step

1 / 4
1

Optional chaining ?. — safe property access

obj?.prop returns undefined instead of throwing a TypeError if obj is null or undefined. Works for nested access (user?.address?.city), method calls (user?.getName()), and array indexing (arr?.[0]). The entire chain short-circuits at the first null/undefined — subsequent parts are not evaluated. Eliminates defensive && chains.

1 of 4
💡Do not overuse optional chaining
Optional chaining can mask real bugs by silently returning undefined where a TypeError would have revealed a coding mistake. Use it for genuinely optional properties (config, user prefs, third-party data) but not for properties that should always exist in correct code — let those throw so you catch the bug early.

🎯 Quick Check

What does 0 ?? 'default' return?

Optional Chaining and Nullish Coalescing: summary

Key points

  • ?. only guards against null and undefined, not other wrong types.
  • Don't overuse it: if a value should always exist, a loud error helps you find the bug.
  • ??= assigns only when the variable is null or undefined.

Frequently asked questions

›What is the difference between ?? and ||?

|| falls back for any falsy value (0, "", false). ?? falls back only for null and undefined.