1. Bitwise Operators
3. Dom Mutations
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:
JSPerf test [here]:
Great place to learn more bit-tricks to make your JS app: Sean Eron Anderson's site [Stanford PhD].