7

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.

Suffick
  • 641
  • 1
  • 6
  • 15

1 Answers1

10

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.

JJJ
  • 32,902
  • 20
  • 89
  • 102
  • `!0` has the added benefit of saving 2 characters and `!1` has the added benefit of saving 3, during minification. Way over-optimized, but if a machine is doing the optimizing, who cares. – Norguard Mar 16 '13 at 07:37