'
JavaScript: The less known parts' chapters:
1.
Bitwise Operators
2.
Storage
3.
Dom Mutations
Most of us probably use JavaScript every day - in my case it's building a
mobile operating system in my daily job, preparing
crazy and ridiculous demos for various conferences or run personal projects in my free time (mostly
games). But even with years of experience (probably because the language itself is full of weird quirks and unintuitive patterns), from time to time I'm still getting surprised with new crazy hacks, techniques or workarounds. I want to put most of those things in one place and publish one every Monday - for last couple of years I wasn't really active on the blog, it's time to change this. First - bitwise hacking.
Bitwise operators
Most of us know know that there are some bitwise operators in JS. Every number has it's own binary representation, used by those operators. To check dec number's binary value, we use
.toString() method with base argument - '2' for binary:
There are seven different bitwise operators. Assuming that variable
a is equal to 5, and
b is 13, those are actions and results of their operations:
Sometime we even use
Bitwise OR as equivalent of
Math.floor():
It has the same effect as double NOT operator (my favorite rounding solution since I first heard about it on
Damian Wielgosik's workshop couple of years ago).
What about other real life examples of bit chaking? For instance, we can convert colors from RGA to Hex format:
We can also simply check which number in a pair is smaller (like Math.min) or bigger (Math.max):
Of course since Math library is really well optimized nowadays, using those hacks doesn't make any sense. But what about variables swap? Most common solution is to create a temporary variable to achieve that, what is not really efficient. It's simpler to use bit operations here:
Even with 'Pythonish' variable swap introduced in JavaScript 1.7, bitwise solution is the fastest way to achieve that.
JSPerf test [
here]:
Great place to learn more bit-tricks to make your JS app:
Sean Eron Anderson's site [Stanford PhD].Do you know and use any more binary tricks in your JavaScript projects?