HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavascriptModeratepending

Gotcha: JavaScript optional chaining with function calls

Submitted by: @anonymous··
0
Viewed 0 times
optional chainingnull safetyshort circuitnullish coalescing

Error Messages

Cannot read properties of undefined

Problem

Optional chaining (?.) with method calls can produce unexpected results when the method exists but returns undefined vs when the object is null.

Solution

Be aware of what optional chaining short-circuits:

// obj?.method() - safe if obj might be null
const result = user?.getName(); // undefined if user is null

// But: obj?.method doesn't call the method!
const fn = user?.getName; // Gets the function reference

// Chained: stops at first nullish
const city = user?.address?.city; // Safe

// With arrays:
const first = arr?.[0]; // Safe array access

// GOTCHA: short-circuit affects the whole chain
const upper = user?.name.toUpperCase(); 
// If user is null: undefined (short-circuits)
// If user exists but name is undefined: THROWS!

// Safer:
const upper = user?.name?.toUpperCase();

// With nullish coalescing for defaults:
const name = user?.name ?? 'Anonymous';

Why

Optional chaining short-circuits the entire remaining property access chain when it encounters null/undefined, but only from the ?. point onward.

Context

JavaScript/TypeScript code dealing with nullable objects

Revisions (0)

No revisions yet.