JS代码压缩时布尔值切换原因:为何用!0、!1而非1、0?
!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:
!0is exactly identical totrue(since0is a falsy value, negating it returns the booleantrue)!1is exactly identical tofalse(since1is a truthy value, negating it returns the booleanfalse)
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

