# Operators & Short-Circuit Evaluation

> What is short-circuit evaluation in JavaScript, and how do the &&, || and ?? operators differ?

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-operators-short-circuit
Last updated: 2026-11-28

Difficulty: Beginner

## Question

What is short-circuit evaluation in JavaScript, and how do the &&, || and ?? operators differ?

## Answer

Short-circuit evaluation means a logical operator stops evaluating as soon as the result is known, and returns one of its operands rather than a boolean. `a && b` returns `a` if it is falsy, otherwise `b`. `a || b` returns `a` if it is truthy, otherwise `b`. `a ?? b` returns `a` unless it is `null` or `undefined`, which makes it the safe choice for default values.

### The operators return operands, not booleans

This is the part people miss. `'' || 'Guest'` evaluates to `'Guest'`, and `'Rahul' && 'Admin'` evaluates to `'Admin'`. The result is only a boolean if the operands are booleans. JavaScript checks truthiness, and only these values are falsy: `false`, `0`, `-0`, `0n`, `''`, `null`, `undefined` and `NaN`. Everything else, including `'0'`, `[]` and `{}`, is truthy.

Because evaluation stops early, the right-hand side may never run. `isLoggedIn && fetchProfile()` only calls `fetchProfile` when `isLoggedIn` is truthy.

### || vs ??: the default value bug

`||` treats every falsy value as "missing". That breaks when `0`, `''` or `false` are legitimate values:

| Value of `a` | \`a \\ | \\ | 10\` | `a ?? 10` |
| --- | --- | --- | --- | --- |
| `0` | `10` | `0` |  |  |
| `''` | `10` | `''` |  |  |
| `false` | `10` | `false` |  |  |
| `null` | `10` | `10` |  |  |
| `undefined` | `10` | `10` |  |  |
| `5` | `5` | `5` |  |  |

If a user sets a discount to `0` or a quantity to `0`, `quantity || 1` silently changes it to `1`. `quantity ?? 1` keeps the zero. Use `??` (ES2020) whenever you mean "if not provided".

### Related operators: ?. and logical assignment

- Optional chaining `?.` (ES2020) short-circuits property access: `order?.customer?.address?.city` returns `undefined` instead of throwing if any link is null or undefined. It pairs naturally with `??`: `order?.customer?.name ?? 'Guest'`.
- Logical assignment (ES2021): `a ||= b` assigns only if `a` is falsy, `a &&= b` only if `a` is truthy, and `a ??= b` only if `a` is null or undefined. `config.retries ??= 3` is the clean way to fill in a default without overwriting an explicit `0`.

### Gotchas worth knowing

- You cannot mix `??` with `&&` or `||` without parentheses. `a || b ?? c` is a SyntaxError; write `(a || b) ?? c`.
- Precedence: `&&` binds tighter than `||`, so `a || b && c` means `a || (b && c)`.
- In React, `{count && <Badge />}` renders a literal `0` when `count` is `0`. Use `{count > 0 && <Badge />}`.
- Do not overuse `&&` for side effects in place of an `if`. It is fine in JSX, but `user && save(user)` as a statement hurts readability.

**&&, || and ?? return operands, not booleans. Compare 0 || "hi", 0 ?? "hi" and "" && "hi" under Tweak.**

1. **ToBoolean(left)**: The left operand is tested for truthiness.
2. **|| returns the first truthy operand**: 0 || "hi" gives "hi" because 0 is falsy.
3. **&& returns the first falsy operand**: "" && "hi" gives "" and never evaluates the right side.
4. **?? only skips null and undefined**: 0 ?? "hi" gives 0, so valid zeros and empty strings survive.

## Code examples

### Operators return operands

```
console.log('' || 'Guest');        // Guest
console.log('Rahul' || 'Guest');   // Rahul
console.log('Rahul' && 'Admin');   // Admin
console.log(0 && 'never reached'); // 0
console.log(null ?? 'default');    // default

// right side is skipped when the result is known
let calls = 0;
const track = () => { calls++; return true; };
false && track();
true || track();
console.log('calls:', calls);      // calls: 0
```

The operators return whichever operand decided the result, and the right side never runs when the left side already settles it.

### Defaults: || vs ?? vs ??=

```
function createOrder(opts) {
  const qtyOr = opts.quantity || 1;     // bug: 0 becomes 1
  const qtyNullish = opts.quantity ?? 1; // keeps 0
  return { qtyOr, qtyNullish };
}
console.log(createOrder({ quantity: 0 }));
console.log(createOrder({}));

const config = { retries: 0, timeoutMs: undefined };
config.retries ??= 3;      // stays 0
config.timeoutMs ??= 5000; // filled in
console.log(config);
```

?? and ??= only treat null and undefined as missing, so a deliberate 0 survives.

### Optional chaining with a fallback

```
const order = { id: 'SWG-42', customer: null };

console.log(order.customer?.address?.city ?? 'Unknown city');
console.log(order.items?.length ?? 0);
console.log(order.notify?.());   // calls only if notify exists

// (order.customer || {}).name  -> old pattern
// order.customer?.name         -> modern pattern
```

?. stops the chain at the first null or undefined and returns undefined, and ?? supplies the fallback.

## Key points

- && and || return one of their operands, not necessarily a boolean
- Falsy values: false, 0, -0, 0n, '', null, undefined, NaN
- Use ?? for defaults when 0, '' or false are valid values
- ?? cannot be combined with && or || without parentheses
- ?. and the logical assignment operators (||=, &&=, ??=) also short-circuit

## Common follow-up questions

- What does \[\] || 'empty' return, and why?
- Why does {count && <List />} sometimes render 0 in React?
- What is the difference between a ||= b and a ??= b?
- How would you write a ?? b without using the ?? operator?

## Interview tips

- Give the quantity = 0 example; it shows you understand why ?? exists
- Say explicitly that the operators return operands, then prove it with a one-liner
- Mention optional chaining and logical assignment to show you know ES2020+ syntax

## Concepts covered

Short-Circuit Evaluation, Logical OR, Nullish Coalescing, Optional Chaining, Logical Assignment

Previous: [Data Types & Type Checking](https://www.internhack.in/learn/interview/javascript-interview/js-data-types) · Next: [String Methods & Template Literals](https://www.internhack.in/learn/interview/javascript-interview/js-string-methods) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [Array Methods (map, filter, reduce)](https://www.internhack.in/learn/interview/javascript-interview/js-array-methods)
- [Destructuring & Spread/Rest](https://www.internhack.in/learn/interview/javascript-interview/js-destructuring-spread)
- [Error Handling (try/catch/finally)](https://www.internhack.in/learn/interview/javascript-interview/js-error-handling)
- [== vs === Equality Operators](https://www.internhack.in/learn/interview/javascript-interview/js-equality-operators)
- [Arrow Functions vs Regular Functions](https://www.internhack.in/learn/interview/javascript-interview/js-arrow-functions)
- [Template Literals & String Interpolation](https://www.internhack.in/learn/interview/javascript-interview/js-template-literals)

## 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)
