0

When JavaScript is used client-side, it has to be transferred over the network, which is why we commonly minify the code, for example by removing whitespace and shortening identifiers (variable and function names, etc).

In JavaScript / ECMAScript, many functions will accept a boolean to trigger certain behavior. For example, DOMTokenList.toggle() or EventTarget.addEventListener(). Using the integers 1 and 0 instead of the boolean values true and false, respectively, when calling upon such functions would save some additional bytes.

However, JavaScript has two comparison operators, == and ===, and while 1 == true would evaluate to true, 1 === true would evaluate to false. Then again, maybe the standard dictates that built-in functions have to be able to deal integers when accepting a boolean or similar. In short, is it safe to replace booleans with integers in the context of built-in functions?

domsson
  • 4,553
  • 2
  • 22
  • 40
  • Safe is a squishy word. One person's "safe" is another person's "crazy risky". I would say you could depend on something like `!0` (on its own) always being evaluated as `true` and `!1` always being evaluated (by itself) as `false`. – Heretic Monkey Jun 21 '21 at 18:58
  • Both examples are not part of ECMAScript but are part of the Web spec. And there's a lot of legacy semantics involved. `JSON.stringify(false)` returns something different than `JSON.stringify(0)` – Jonas Wilms Jun 21 '21 at 19:02
  • Unless you analyze the code and check all the places that use the value, so you can tell whether it just checks its "truthiness" or performs type-specific checks, you have to be conservative in your transformations. – Barmar Jun 21 '21 at 19:09
  • Related / possibly duplicates: https://stackoverflow.com/questions/20567523/javascript-minification-why-is-false-replaced-with-1-and-true-with-0, https://stackoverflow.com/questions/48381308/reason-for-boolean-switching-when-minifying-js/48381354 – crashmstr Jun 21 '21 at 19:24

1 Answers1

1

It depends on the built-in function. For some, passing an integer produces the same result as passing a boolean, for others it doesn't. In general, yes, if a function expects a boolean it will attempt to coerce any value into a boolean, but there are probably exceptions.

However, a minifier does in general not know whether a function call is a call to a builtin function, or what the function's signature is. The first goal is to be correct (not introducing bugs), not to output the smallest bundle.

A standard trick that minifiers do employ, and which is always equivalent, is replacing false with !1 and true with !0.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375