Optional Chaining & Nullish Coalescing
JS جاوااسکریپت

Optional Chaining & Nullish Coalescing

Safely access nested properties and choose defaults without `||` bugs.

BugCast Admin··۵ دقیقه مطالعه

?. and ?? are modern JavaScript essentials for defensive property access and correct default values. Interviewers love comparing ?? vs ||.

Common Interview Questions

Q: What does optional chaining short-circuit?

Answer: If the base is null or undefined, ?. stops evaluation and returns undefined without throwing. Works for properties, calls, and brackets.


const city = user?.address?.city;
const result = maybeFn?.();

Q: ?? vs || for defaults?

Answer: Nullish coalescing only falls back on null or undefined. Logical OR falls back on any falsy value including 0, '', and false.


const count = 0 || 10;  // 10 — wrong
const count2 = 0 ?? 10; // 0 — correct

Q: Can you chain ?? with ?.?

Answer: Yes — common pattern for safe access with fallback. Mind operator precedence; use parentheses when mixing with && or ||.


const label = user?.profile?.name ?? "Guest";

Q: Optional chaining with arrays?

Answer: Bracket optional chaining ?.[index] safely accesses array elements or dynamic keys.


const first = data?.items?.[0]?.id;

Key Points for Interviews

  • ?. prevents 'cannot read property of undefined' errors

  • Use ?? when 0 or '' are valid values

  • Do not over-chain — deep optional chains may signal bad data contracts

  • Supported in all modern browsers and Node 14+

  • TypeScript mirrors these operators in type narrowing

#optional-chaining#nullish#interview

مطالب مرتبط