Alexander Dickson

How to write tiny JavaScript

JavaScript is unique in that its dominant use is client side scripting in web browsers, in which its source needs to be delivered via HTTP. This means that the size of the source code is significat: it affects the load time of the browser. People also like writing their JavaScript as small as possible, generally for competitions with byte size constraints. This article is mainly for people entering these competitions and also implementing minifiers/packers.

I’ll try and skip over the obvious ones to show some tips I’ve discovered.

Drop verbose literals

You can convert true and false into !0 and !1, respectively.

Many zeros bad

If you have a number such as 3000 (possibly used with setTimeout()/setInterval()), you can save a character by using exponential notation, e.g. 3e3.

Floor it!

If you need to drop the decimal portion of a floating point number (like Math.floor()), you can use ~~ (double flip bits). Be warned, however, that this doesn’t floor for negative numbers, and it also has the side effect of truncating the Number to 32 bits. You can also use | 0 (bitwise OR with 0).

Drop semi-colons

If it makes sense to drop the semi-colon, then do it. This is not as often as you might think, once you’ve removed \ns.

indexOf() trick

When using String or Array’s indexOf() method, add a ~, which will make the expression truthy or falsey depending if the element was found.

Keep digging!

There are many other methods at reducing your code on a character level, so get experimenting.


Want to discuss this post? Just mention me @alexdickson.