iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Bitwise

Bitwise operators treat numbers as 32-bit integers. They're rare in everyday business logic but unbeatable for flags, hash mixing, and graphics math.

The operators

OperatorMeansExample
&AND0b1100 & 0b10100b1000
|OR0b1100 | 0b10100b1110
^XOR0b1100 ^ 0b10100b0110
~NOT (unary)~5-6
<<Shift left (× 2 per step)1 << 416
>>Arithmetic shift right-8 >> 1-4
>>>Unsigned shift right-1 >>> 04294967295

Flag fields

JS
const PERMISSIONS = { READ: 1, WRITE: 2, ADMIN: 4 };

// Combine
let mine = PERMISSIONS.READ | PERMISSIONS.WRITE;        // 3

// Test
if (mine & PERMISSIONS.READ) { /* yes */ }

// Add / remove
mine |= PERMISSIONS.ADMIN;
mine &= ~PERMISSIONS.WRITE;

Handy patterns

PatternTrick
Floor to integer (positives)x | 0 or ~~x
Multiply by 2 / power of 2x << n
Check oddx & 1
Swap without tempa ^= b; b ^= a; a ^= b; (don't actually do this)
Warning: Bitwise operators convert to 32-bit signed integers. Anything outside that range loses precision: (2 ** 32) | 0 = 0. Use BigInt for larger needs.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Bitwise!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Use the bitwise OR to combine two permission flags.

const mine = READ WRITE;

Test yourself

Q1. `5 & 3` is…
Q2. Combine flags with…
Q3. Bitwise operators convert numbers to…

Discussion

Loading…