gotchaMinorpending
JavaScript optional chaining returns undefined not null
Viewed 0 times
optional chainingundefined vs nullshort-circuitnullish coalescing?.
browsernodejs
Error Messages
Problem
Optional chaining (?.) always returns undefined when the chain short-circuits, even if the nullish value was null. This matters when you need to distinguish between null and undefined.
Solution
obj?.prop returns undefined if obj is null OR undefined. It never returns null from short-circuiting. If you need to preserve null vs undefined distinction, use explicit checks. Also: ?. does not work on the left side of assignment (obj?.prop = value is invalid).
Why
Optional chaining was designed to simplify null/undefined checks, not to preserve the specific nullish type. The operator short-circuits to undefined regardless of whether the base was null or undefined.
Revisions (0)
No revisions yet.