Is !0 and !1 something more than a shorthand for true/false? [duplicate]
Asked Answered
C

1

10

Reading through some code, I came across the use of !0 and !1. I realize that these are shorter ways of writing true and false.

!0 === true
!1 === false

This of course save a few bytes, but is there some other reason to use it?

Is there a name for this way of writing it?

Curler answered 1/9, 2012 at 21:45 Comment(4)
Yes - "confusing and lacking readability" ;)Philip
I prefer !!0 (false) and !!1 (true) for much more clarity and only a 50% size increase! No. Really, use the keywords ..Ciri
@pst Thanks for that, makes much more sense. !0 being true is really easy to misread.Curler
If you want to know how affects performance, go to jsperf.com/checking-if-true-or-false and run the testsCurson
K
8

Most JavaScript minification tools, like UglifyJS, generate that code because it's shorter and semantically equivalent. For example, given:

var x = true;
if (x) { 
  alert(x); 
}

UglifyJS will generate var x=!0;x&&alert(x).

Usually, you don't need to write code using that style; let the minifiers do their work :-).

Kinaesthesia answered 1/9, 2012 at 21:47 Comment(1)
Thanks! I sensed it was the work of a minifier, just wanted to make sure there wasn't something more to it that I was missing.Curler

© 2022 - 2024 — McMap. All rights reserved.