什么是短路求值
What is short-circuit evaluation
一句话:&& 和 ||结果一旦确定就不再算右边, 而且它们返回的是操作数本身,不是布尔值。
a && b—— a 为假就返回 a,否则返回 b。「都真才真」, 所以遇到假就可以收工。a || b—— a 为真就返回 a,否则返回 b。a ?? b(空值合并)——只有 a 是null或undefined时才返回 b。
|| 和 ??的区别是高频追问,而且是真实 bug 来源:count || 10 在 count 为0 时会给出 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 isnullorundefined.
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.