JavaScript shortcuts for TRUE and FALSE

Ciprian on Friday, April 8, 2022 in Methods, Events and Scopes

NEW! Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

Here’s a neat trick if you’re into micro-optimization. JavaScript compressors and minifers are used to make JavaScript code smaller and, usually, unreadable.

Compressing JavaScript Code

Compressing this JavaScript code:

let foo = true,
    bar = false;

Results in this compressed code:

let foo=!0,bar=!1; 

So what’s interesting is how the compressor treats literals such as true and false into smaller units. You see that true is represented with !0 and false with !1.

Reading it carefully, we can see that true has been changed into “not zero”. “zero” is usually an indicator of false, so in this case, “not zero” means it’s true. And, obviously, it’s the other way around with “not one”.

Now you can update your code and save 2 or 3 bits for every boolean operator :)

Related posts

Leave a Reply

You have to agree to the comment policy.

Follow me!

If you like this article, go ahead and follow me on Twitter or buy me a coffee to support my work!

Follow @getButterfly