Skip to content Skip to sidebar Skip to footer

Reason For Boolean Switching When Minifying Js

I have this line of code in a js file var useScroll = Window.innerWidth > 1360 ? true : false; When it's minified it becomes i=Window.innerWidth>1360?!0:!1 I was just curio

Solution 1:

The ! operator does casting. So !0 becomes true and !1 becomes false. However, 0 and 1 are numbers, not booleans.


Solution 2:

There is a very valid reason. 1 and 0 are integeers, and does sometimes behave different than booleans.

However the ! operator includes casting, which menas that !0 and !1 are acutal booleans, but they are shorter to type than false and true. And that is the reason they are beeing used.

Example where they behave different:

var a = (1 === true); //a will be false
var a = (!0 === true); //a will be true

However you can simplify your code to

i=Window.innerWidth>1360

since Window.innerWidth>1360 will be either true or false which is exactly what you are looking for.


Solution 3:

if you do !0 or !1 it will become a boolean, if you remove ! it will be an integer...

And instead of doing

Window.innerWidth > 1360 ? true : false

do

Window.innerWidth > 1360

Solution 4:

The ! is (logical NOT) operator So !0 become true and !1 becomes false. Where only 0 and 1 are numbers not boolean.

var n1 = !true;  // !t returns false
var n2 = !false; // !f returns true
var n3 = !'Cat'; // !t returns false

So, both have a different meaning by data types.

i=Window.innerWidth>1360?1:0 This is also valid as you told but when you want data type as boolean you can't get by using this expression.


Post a Comment for "Reason For Boolean Switching When Minifying Js"