DrillLab
第 19 / 105 道19 / 105 · #281

什么是短路求值

What is short-circuit evaluation

先自己答,再往下看Answer it yourself first

一句话:&&||结果一旦确定就不再算右边, 而且它们返回的是操作数本身,不是布尔值

  • a && b—— a 为假就返回 a,否则返回 b。「都真才真」, 所以遇到假就可以收工。
  • a || b—— a 为真就返回 a,否则返回 b。
  • a ?? b(空值合并)——只有 a 是 nullundefined才返回 b。

||??的区别是高频追问,而且是真实 bug 来源:count || 10count0 时会给出 10—— 因为 0 是假值。要默认值就用 ??

React 里最常见的用法是条件渲染:{loading && <Spinner />}坑在这儿:如果左边是list.length 而列表为空,0 && … 返回 0, 而 React 会把 0 渲染出来—— 页面上凭空多一个「0」。 所以要写成 list.length > 0 && …

In one line: && and || stop evaluating the moment the result is decided, and they hand back an operand, not a boolean.

  • a && b — returns a if a is falsy, otherwise b. “Both must be true”, so one falsy value ends the job.
  • a || b — returns a if a is truthy, otherwise b.
  • a ?? b (nullish coalescing) — returns b only when a is null or undefined.

The difference between || and ?? is a frequent follow-up and a real source of bugs: count || 10 gives you 10 when count is 0, because 0 is falsy. For default values, reach for ??.

The most common React use is conditional rendering: {loading && <Spinner />}. Here is the trap: if the left side is list.length and the list is empty, then 0 && … returns 0, and React renders that 0 — a stray “0” shows up on the page out of nowhere. Write list.length > 0 && … instead.

JSX短路的三个实际用法与两个坑Three real uses of short-circuiting, and two traps示意Illustrative
1// 短路返回的是操作数本身
2console.log(1 && 2); // 2
3console.log(0 && 2); // 0 ← 不是 false
4console.log("" || "默认"); // "默认"
5
6// || 和 ?? 的区别
7const count = 0;
8count || 10 // 10 ✗ 0 被当成「没传」
9count ?? 10 // 0 ✓
10
11// React 条件渲染的经典坑
12{list.length && <List />} // ✗ 空列表时页面上多一个 0
13{list.length > 0 && <List />} // ✓
14{list.length ? <List /> : null} // ✓ 也可以
1// Short-circuiting returns the operand itself
2console.log(1 && 2); // 2
3console.log(0 && 2); // 0 ← not false
4console.log("" || "default"); // "default"
5
6// The difference between || and ??
7const count = 0;
8count || 10 // 10 ✗ 0 is treated as "nothing was passed"
9count ?? 10 // 0 ✓
10
11// The classic React conditional-rendering trap
12{list.length && <List />} // ✗ an empty list prints a stray 0 on the page
13{list.length > 0 && <List />} // ✓
14{list.length ? <List /> : null} // ✓ this works too