Today I Learned - Rocky Kev

TIL the XOR operator in Javascript

POSTED ON:

TAGS:

The bitwise XOR operator (^) returns a 1 in each bit position for which the corresponding bits of either but not both operands are 1s.
The operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones).

const a = 5;        // 00000000000000000000000000000101
const b = 3; // 00000000000000000000000000000011

console.log(a ^ b); // 00000000000000000000000000000110
// expected output: 6

I haven't really found real good use-cases of why a person would use it.
As noted in a comment, "XOR is a pretty neat party trick."

But it's used in Cryptographic algorithms.

XOR is used in cryptography for two main reasons: it is reversible e.g if A xor with B results in C then A xor with C will give B. it makes equal probability of 0 and 1 unlike AND & OR. if AND is used, there are 75% chances of output 0 and 25% of 1,if OR is used, there are 75% chances of output 1 and 25% of 0 so '1' and '0' output is not uniformly distributed and thus will not create randomness.
https://security.stackexchange.com/a/220699

MDN:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_XOR


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.