You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS代码压缩时布尔值切换原因:为何用!0、!1而非1、0?

Why Do Minifiers Use !0/!1 Instead of 1/0 for Boolean Values?

Great question—this is a common point of confusion when looking at minified JavaScript, so let's break it down clearly.

First, let's establish the core equivalences here:

  • !0 is exactly identical to true (since 0 is a falsy value, negating it returns the boolean true)
  • !1 is exactly identical to false (since 1 is a truthy value, negating it returns the boolean false)

Now, why not just use 1 and 0 instead? Here are the key reasons:

1. Preserving Type Consistency

Your original code defines useScroll as a boolean (true/false). If the minifier replaced those with 1/0, the variable would become a number instead. While loose equality (==) or basic condition checks (if (i)) would treat 1 like true and 0 like false, strict equality checks (===) would break entirely.

For example, if your code later included:

if (useScroll === true) {
  // Execute scroll-related logic
}

Using 1 instead of true would make this condition fail every time (since 1 === true evaluates to false). Minifiers prioritize keeping your code's logic intact, so preserving the original boolean type is critical to avoid subtle bugs.

2. No Length Advantage

!0 and 1 are both 2 characters long; !1 and 0 are also 2 characters. There's no byte-saving benefit to using numbers over the negated falsy/truthy values, so the minifier doesn't gain anything by switching types.

3. Standard Minifier Behavior

Tools like Terser or UglifyJS (the most common JS minifiers) default to this pattern because it's a safe, reliable way to compress boolean values without altering the code's underlying semantics. It's an industry convention that balances compression efficiency with compatibility.

To sum it up: using !0/!1 keeps your variable a boolean (matching the original code's intent) while achieving the same level of compression as using numbers. Using 1/0 would risk breaking strict equality checks down the line, which isn't worth the non-existent byte savings.


内容的提问来源于stack exchange,提问作者Sean T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:56:02