Javascript minification why is false replaced with !1 and true with !0 [duplicate]

天大地大妈咪最大 提交于 2020-01-01 07:57:04

问题


I'm writing an app using Enyo2 which comes with a minification tool based on UglifyJS. I've noticed that:

var t = false

is replaced with

var t=!1

The same way true is replaced with !0. I'm sure there is a good explanation for that, I just can't find it. Any idea?


回答1:


There is one apparently. If you use 1 or 0 to translate true or false, it would be shorter but seen as integers. If you add ! in front and reverse them, it will be coalesced into booleans and still be short.




回答2:


It is the smallest non-ambiguous way to express the value.

true uses 4 characters on the wire and false uses 5 characters. !1 & !0 use 2 characters.




回答3:


In JavaScript, 0 is a falsy value. This means that 0 equates to false when represented as a boolean type. 1 on the other hand; or any other positive number for that matter, is not a falsy value and will equate to true.

Here we could just set:

t = 0; // false
t = 1; // true

The problem with this is that these values are integers (numbers) and not boolean values (true or false). Using a strict equality check (===) we'd find:

t = 0;
t == false; // true
t === false; // false

The ! operator performs a logical NOT operation on the value, and can be used as a quick way to convert any value to boolean:

t = !1;
t == false; // true
t === false; // true

Performance-wise, there is not really much difference between if (!t) and if (t == true), however in minification terms this reduces our JavaScript by 7 bytes, allowing it to be downloaded ever so slightly quicker.




回答4:


Negation converts a non-boolean, but truthy value to a pure boolean.

I ran this in Chrome Developer Tools:

> !1
false
> !0
true

Therefore, !1 is interchangeable with false and !0 is interchangeable with true. So now that we know it's safe to change it, the next question is why. Well, because it's fewer bytes. The point of minification is to make the code smaller, but compatible.

Long-story short, it's a safe way to compress the literal true and false so they take less space when transmitting over the wire.



来源:https://stackoverflow.com/questions/20567523/javascript-minification-why-is-false-replaced-with-1-and-true-with-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!