# Optional Chaining and Nullish Coalescing

> Explain the optional chaining (?.) and nullish coalescing (??) operators. How do they differ from && and ||, and when should you use each?

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-optional-chaining-nullish
Last updated: 2026-11-28

Difficulty: Beginner

## Question

Explain the optional chaining (?.) and nullish coalescing (??) operators. How do they differ from && and ||, and when should you use each?

## Answer

Optional chaining (`?.`) safely accesses a property, calls a method or indexes into a value that might be `null` or `undefined`: if the left side is nullish, the whole expression short-circuits to `undefined` instead of throwing a `TypeError`. Nullish coalescing (`??`) returns the right-hand operand only when the left is `null` or `undefined`, unlike `||`, which falls back on any falsy value such as `0`, `''` or `false`. Both arrived in ES2020 and are supported in every modern browser and Node.js 14+.

### The three forms of optional chaining

- `obj?.prop`: property access
- `obj?.[expr]`: computed access, for example `orders?.[0]`
- `fn?.(args)`: call only if `fn` is not nullish, useful for optional callbacks like `onSuccess?.(data)`

Short-circuiting covers the rest of the chain. In `user?.address.city`, if `user` is nullish the result is `undefined` and `.city` is never evaluated. But if `user` exists and `address` is `undefined`, `.city` still throws, so you need `user?.address?.city` when each level may be missing.

### Why ?? is different from ||

`||` treats every falsy value as missing: `false`, `0`, `-0`, `0n`, `''`, `NaN`, `null`, `undefined`. That causes real bugs:

| Value of `a` | \`a \\ | \\ | 'default'\` | `a ?? 'default'` |
| --- | --- | --- | --- | --- |
| `0` | `'default'` | `0` |  |  |
| `''` | `'default'` | `''` |  |  |
| `false` | `'default'` | `false` |  |  |
| `NaN` | `'default'` | `NaN` |  |  |
| `null` or `undefined` | `'default'` | `'default'` |  |  |

If a cart's discount is legitimately `0` rupees, `discount || 50` silently applies a fifty rupee default. `discount ?? 50` keeps the `0`. Use `??` for defaults whenever `0`, `''` or `false` are valid values; use `||` only when any falsy value really should be replaced.

### Comparison with && chains

Before ES2020 people wrote `user && user.address && user.address.city`. That works but returns the first falsy value it meets: if `user.address` is `''`, the result is `''`, not `undefined`. Optional chaining only checks for `null` and `undefined`, so `?.` is both shorter and more precise.

### Rules and gotchas

- `??` cannot be mixed with `&&` or `||` without parentheses: `a || b ?? c` is a `SyntaxError`. Write `(a || b) ?? c`.
- `?.` cannot be on the left of an assignment: `user?.name = 'x'` is a `SyntaxError`.
- `new Foo?.()` and optional chaining in tagged templates are not allowed.
- Do not sprinkle `?.` everywhere. If a value must exist (for example a required API field), let the code throw so the bug surfaces instead of hiding it as `undefined`.
- Logical assignment operators (ES2021) build on this: `config.timeout ??= 5000` assigns only if the current value is nullish, and `count ||= 1` assigns if it is falsy.
- `?.` checks only the value immediately to its left; `obj.method?.()` still throws if `obj` itself is undefined.

**?? vs ||: keeping valid falsy values. Switch the operator between ?? and || under Tweak and watch 0 survive or get replaced.**

1. **?? checks for null/undefined only**: 0 ?? "hi" returns 0.
2. **|| checks truthiness**: 0 || "hi" returns "hi", which loses a valid zero.
3. **Use ?? for defaults**: settings.volume ?? 50 keeps a user's 0.

## Code examples

### Optional chaining patterns on an API response

```
const response = {
  data: {
    restaurant: { name: 'Meghana Foods', ratings: [4.5, 4.2] },
  },
};

console.log(response.data?.restaurant?.name);
console.log(response.data?.offers?.[0]?.code);   // offers missing
console.log(response.data?.restaurant?.ratings?.[1]);

const callbacks = { onSuccess: msg => `ok: ${msg}` };
console.log(callbacks.onSuccess?.('paid'));
console.log(callbacks.onError?.('failed'));      // no onError, no crash

// Short-circuit: the function is never called when user is null
const user = null;
let calls = 0;
user?.profile[(calls++, 'name')];
console.log('calls:', calls);
```

Each ?. stops evaluation when the value to its left is nullish, including any expressions later in the chain. Optional calls are handy for callbacks that may not be provided.

### ?? vs || and logical assignment

```
function buildConfig(options) {
  return {
    retries: options.retries ?? 3,
    retriesWrong: options.retries || 3,
    label: options.label ?? 'Untitled',
    verbose: options.verbose ?? true,
  };
}

console.log(buildConfig({ retries: 0, label: '', verbose: false }));

const settings = { timeout: null, theme: 'dark' };
settings.timeout ??= 5000; // assigned: was null
settings.theme ??= 'light'; // skipped: already set
console.log(settings);
```

?? respects intentional zero, empty string and false values, while || overwrites them. The ??= operator assigns only when the current value is null or undefined.

## Key points

- ?. returns undefined instead of throwing when the left side is null or undefined, and short-circuits the rest of the chain.
- ?? falls back only on null and undefined; || falls back on every falsy value.
- Use ?? for numeric, string and boolean defaults where 0, '' or false are valid.
- Mixing ?? with && or || requires parentheses.
- Optional chaining cannot be used on the left side of an assignment.
- ??= and ||= are the logical assignment counterparts from ES2021.

## Common follow-up questions

- What does a?.b.c return if a exists but b is undefined?
- Why is a || b ?? c a syntax error?
- How would you set a default for a function parameter, and how does that differ from ???
- What is the difference between ??= and ||=?

## Interview tips

- Give a concrete bug that || causes, such as a zero quantity or a zero price being replaced by a default.
- Mention short-circuiting: the rest of the chain is not evaluated, which also skips side effects.
- Say that overusing ?. can hide bugs; strong candidates know when a crash is preferable.

## Concepts covered

Optional Chaining, Nullish Coalescing, Short-circuit Evaluation, Falsy Values, Logical Assignment

Previous: [Generator Functions](https://www.internhack.in/learn/interview/javascript-interview/js-generators) · Next: [Currying and Function Composition](https://www.internhack.in/learn/interview/javascript-interview/js-currying-composition) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [Memoization](https://www.internhack.in/learn/interview/javascript-interview/js-memoization)
- [Property Descriptors and Object.defineProperty](https://www.internhack.in/learn/interview/javascript-interview/js-property-descriptors)
- [Deep Cloning: structuredClone vs JSON](https://www.internhack.in/learn/interview/javascript-interview/js-structuredclone)
- [JavaScript Design Patterns](https://www.internhack.in/learn/interview/javascript-interview/js-design-patterns)
- [Memory Leaks in JavaScript](https://www.internhack.in/learn/interview/javascript-interview/js-memory-leaks)
- [Custom Error Types and Error Handling](https://www.internhack.in/learn/interview/javascript-interview/js-error-types)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
