Tiny JavaScript Tricks
Most of these tricks, build systems will do for you, so this isn’t something to be worried about during development. But if for whatever reason, you don’t have a build process, or you’re doing a programming problem, here’s some tricks to save even more space.
Boolean Literals
true and false can be changed to !0 and !1 respectively. Quick tip, but easily understood.
Exponential Notation
Numbers that have a lot of zeros in them, commonly used for setTimeout()/setInterval() durations. For instance, if you want to do something after 3 seconds, you would specify it as 3000 milliseconds. A number that’s a multiple of ten can be easily expressed using expoential notation. In this instance, that would be 3e3 . It’s basically saying 3, with 3 zeros after it.
Hit the Floor
If you want to drop the decimal portion of a number, similar to Math.floor() , it’s easy to do by using ~~ in front of the number. This will flip the bits of a number, whilst converting it to a 32 bit number, then flip it back again. During this process, the decimal portion gets dropped.
~~3.159 -> 3 ~~-56.45 -> -56
You could also use the OR operator with a zero (bitwise OR with zero), for example, -4.50|0 . This will achieve the same effect.
Do note, it will cause issues with any number that’s not 32 bits. Let’s face it, who actually deals with numbers that big? 😛
IndexOf Trick
If you’ve done JavaScript development at all, you’ve undoubtedly wrote code to test if an item is in an array. For whatever reason, arrays don’t have a .contains() method, so to get around that, you do something in the vein of:
if ([1,2,3].indexOf(2) > -1) { ... }
Using the power of the tilde again, we can shorten that to:
if (~[1,2,3].indexOf(2)) { ... }
Drop Semicolons (Use with Caution)
Now this is something to be done with care as it can cause undesired side effects, but semicolons aren’t always required at the end of a statement.
The JavaScript interpreter will insert semicolons where it thinks they should be based on a set of rules. Those rules can be JavaScript Semicolons but they are confusing to say the least.
If you’re looking to save space and you’re removing semicolons, make sure you test it before deploying it.
Find Your Own
Although you may not use this when developing a client application as a build system will do this compression for you, but if you’re looking to squeeze everything you can from that JavaScript CodeEval problem, some of these tricks might give you a leg up.
JavaScript is such a flexible language that there’s plenty of small gimmicks that it will let you do to save space.
Got any tricks of your own, share them down in the comments.