Volume 2

Q128: Optional Chaining, Nullish Coalescing and Safe Defaults

Difficulty: SeniorFrequency: HighAnswer time: 8-12 minutes

What Interviewers Want To Evaluate

This question checks whether you understand safe property access and defaulting semantics. Interviewers want ?., ??, ||, optional calls, optional element access, short-circuiting, invalid left-hand assignment, and when these operators hide data quality problems.

Senior answers should connect these tools to API integration, form values, configuration, and defensive UI rendering.

Short Interview Answer

Optional chaining safely reads through null or undefined without throwing. Nullish coalescing provides a default only when the left side is null or undefined. This differs from ||, which defaults for all falsy values such as 0, false, and empty string. These operators are useful for uncertain data, but overusing them can hide broken contracts that should be validated earlier.

Detailed Interview Answer

Optional chaining helps when part of a path may be missing.

const city = user.profile?.address?.city;

If profile or address is null or undefined, the expression returns undefined instead of throwing.

Property Access

Without optional chaining:

const city = user.profile.address.city;

This throws if profile is missing.

With optional chaining:

const city = user.profile?.address?.city;

The access becomes safe for nullish intermediate values.

Optional Element Access

Optional chaining works with bracket access.

const firstItem = response.items?.[0];
const value = dictionary?.[key];

This is useful for arrays, dictionaries, and dynamic keys.

Optional Calls

Optional chaining can call a function only if it exists.

onComplete?.(result);

This is common for optional callbacks.

If onComplete exists but is not callable, it still throws.

Nullish Coalescing

?? defaults only for null or undefined.

const pageSize = input.pageSize ?? 20;

If pageSize is 0, the result remains 0.

Difference From ||

|| defaults for any falsy value.

const count = 0 || 10; // 10
const safeCount = 0 ?? 10; // 0

This distinction matters for:

0
false
""
NaN

Use ?? when absence means only null or undefined.

Short-Circuiting

Optional chaining short-circuits only along the optional chain.

const value = user?.profile.name;

This protects user, but if profile exists as undefined, .name can still throw depending on how the chain is written.

Safer:

const value = user?.profile?.name;

Invalid Assignment

Optional chaining cannot be used as an assignment target.

user.profile?.name = "Meera"; // invalid

You must ensure the object exists before assigning.

if (user.profile) {
  user.profile.name = "Meera";
}

Safe Defaults

Defaults should respect the domain.

const label = user.displayName ?? user.email ?? "Unknown user";

This makes fallback order clear.

But if displayName should always exist after validation, defaulting everywhere may hide broken data.

API Boundary Pattern

Normalize external data once.

function normalizeUser(raw) {
  return {
    id: String(raw.id),
    name: raw.name ?? "Unknown",
    avatarUrl: raw.profile?.avatarUrl ?? null,
  };
}

The rest of the app can then use a predictable shape.

Common Mistakes

A common mistake is replacing all property access with optional chaining.

order?.payment?.card?.brand

If payment is required by the business flow, this may hide an invalid state. Validation or an error state may be better.

Another mistake is using || for numeric or boolean defaults.

Senior Trade-Offs

Use optional chaining for genuinely optional data. Use validation for required contracts.

Use nullish coalescing when 0, false, or empty string are valid values.

Good code distinguishes absence from valid falsy values.

Code or Design Example

function getPagination(input) {
  return {
    page: input.page ?? 1,
    pageSize: input.pageSize ?? 25,
    showArchived: input.showArchived ?? false,
  };
}

This preserves explicit false and 0 if the domain allows them.

Debugging Workflow

When defaults behave incorrectly:

check null vs undefined
check valid falsy values
check || defaulting
check optional chain placement
check required vs optional contract
normalize API data at boundaries
add tests for 0, false, empty string, null, undefined

Interview Framing

Compare ?., ??, and || with examples involving 0 and false. Then discuss when safe access hides broken contracts.

Revision Notes

Optional chaining protects against null and undefined. Nullish coalescing defaults only for null and undefined.

Key Takeaways

Safe access is helpful, but safe data contracts are better. Use these operators where optionality is real.

Follow-Up Questions

  1. What does optional chaining do?
  2. What values does it short-circuit on?
  3. What is optional call syntax?
  4. What does ?? default on?
  5. How is ?? different from ||?
  6. Why is 0 || 10 risky?
  7. Can optional chaining be assigned to?
  8. When can optional chaining hide bugs?
  9. Where should API data be normalized?
  10. How do you test safe defaults?

How I Would Answer This In A Real Interview

I would say optional chaining safely reads through nullish values and ?? defaults only for null or undefined. Then I would contrast ||, mention valid falsy values, and explain that required data should be validated rather than hidden behind optional access.