Suffick Suffick - 3 months ago 12
Javascript Question

Is !0 and !1 better than 1 and 0?

I noticed that Closure Compiler compiles true and false (or 1 and 0) as !0 and !1. This doesn't make sense to me since it's twice as many characters as 1 and 0. Is there a reason for this? Is there any benefit?

Thanks.

Answer

1 !== true and 0 !== false, but !0 === true and !1 === false. The compiler just makes sure the type stays boolean.

Consider this example:

var a = true;

if( a === true ) {
    console.log( 'True!' );
}

if( a === 1 ) {
    console.log( 'You should never see this.' );
}

If you change the first line to var a = 1; the first conditional would be false and the second true. Using var a = !0; the script would still work correctly.