Search code examples
javascriptminify

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 curious, why have the ! operator? To me it makes more sense to just be.

i=Window.innerWidth>1360?1:0

Solution

  • 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.