Shaving Bytes with JavaScript Booleans
Developers are always search for ultimate way to create something with the least amount of code. This, of course, is one of the reasons we use minifiers: to serve code as small as possible. Of course this practice has numerous benefits, like faster download time, less storage consumption, etc. One way that minifiers are able to shave bytes off of JavaScript code is changing the way booleans are used.
true === !0 // Save 2 chars
false === !1 // Save 3 chars
A few bytes of every true and false go away with the ! evaluation. If you set one-letter variables names to those values, you may end up saving more. Keep in mind I'm not telling you to do this in your source code -- minifiers like Uglify JS will do this for you. Just something neat to know about though!
With CSS border-radius, I showed you how CSS can bridge the gap between design and development by adding rounded corners to elements. CSS gradients are another step in that direction. Now that CSS gradients are supported in Internet Explorer 8+, Firefox, Safari, and Chrome...
I love almost every part of being a tech blogger: learning, preaching, bantering, researching. The one part about blogging that I absolutely loathe: dealing with SPAM comments. For the past two years, my blog has registered 8,000+ SPAM comments per day. PER DAY. Bloating my database...
Note: For this tutorial, I'm using version1 of the Google Translate API. A newer REST-based version is available.
In an ideal world, all websites would have a feature that allowed the user to translate a website into their native language (or even more ideally, translation would be...
Note: This post has been updated.
One of my huge web peeves is when an element has click events attached to it but the element doesn't sport the "pointer" cursor. I mean how the hell is the user supposed to know they can/should click on...
Cool :-)
Glad you aren’t advocating coding like this directly. Can’t beat true/false for readability.
Coercions like
Number
toBoolean
doesn’t affect performance?Maybe too simple of a test: http://jsperf.com/bool-num-test
Looks like using
!0
and!1
may be faster (in Chrome 35) but only marginally.Even if that’s true, and it’s not due to some statistical error, the gain is so small it’s not really worth it.
Those are noops anyway. I would be surprised if the JS engine just optimise them away at compile time.
didn’t just*
Still prefer true/false for readability. As you said, it is better to let the Minifier to do this for us. It is better to keep the true/false in our code.
I expect the gain to be lost as soon as the file gets gzipped. I am wrong?
You should also remember the bitwise operations like
!~number, that returns true only for -1