Bitwise AND, OR, XOR and NOT in JavaScript
Intermediate · 4 min read
Inside the computer, every whole number is a row of bits, each one either 0 or 1. Bitwise operators work on those bits directly, one position at a time. They are how you pack many yes/no settings into one number: file permissions, feature flags, game controller buttons, and the options passed to many system functions.
In this tutorial you will work out AND, OR, XOR and NOT by hand, check the answers in JavaScript, and then use them to give, check and remove permissions stored in a single number. You need to know what binary is (each place is worth 1, 2, 4, 8 and so on) and toString(2).
Line the numbers up
We will use 12 and 10. In binary:
12 = 1100 (8 + 4)
10 = 1010 (8 + 2)
Each operator compares the two numbers column by column:
- AND (
&) gives 1 only where both bits are 1. - OR (
|) gives 1 where either bit is 1. - XOR (
^, "exclusive or") gives 1 where the bits are different. - NOT (
~) takes one number and flips every bit.
Work them out on paper:
1100 1100 1100
AND 1010 OR 1010 XOR 1010
= 1000 = 1110 = 0110
= 8 = 14 = 6
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
68 AND, OR, XOR and NOT
fairWork out 12 & 10, 12 | 10, 12 ^ 10 and ~12 by hand, then check them. Use the operators to set, test and clear flags in a permissions byte, and show that & and && are unrelated.
Stuck? Three hints, smallest first
- 1. Line the numbers up in binary: 12 is 1100 and 10 is 1010.
- 2.
~xis-x - 1, because the bits include the sign. - 3. Clear a flag with
value & ~flag, and toggle it withvalue ^ flag.
Step 1: check the paper answers
console.log(12 & 10, 12 | 10, 12 ^ 10); // 8 14 6
console.log((12 & 10).toString(2), (12 | 10).toString(2), (12 ^ 10).toString(2)); // 1000 1110 110
They match. The XOR result prints as 110 rather than 0110, because toString drops leading zeros.
Step 2: NOT looks wrong at first
You might expect ~12 to flip 1100 into 0011, which is 3. It doesn't:
console.log(~12, ~0, ~-1); // -13 -1 0
JavaScript's bitwise operators work on 32-bit signed whole numbers. 12 is really thirty-two bits, with 28 zeros in front. NOT flips all of them, including the leftmost bit, which is the sign bit: when it is 1, the number is negative. The result works out as -x - 1 every time, so ~12 is -13, ~0 is -1 and ~-1 is 0.
So ~ is not a true/false flip. For that, use !.
Step 3: permissions as flags
Give each permission its own bit, using powers of two so that no two share a bit:
const READ = 1; // 001
const WRITE = 2; // 010
const EXEC = 4; // 100
const grant = (perms, flag) => perms | flag;
const readWrite = grant(grant(0, READ), WRITE); // 3
const all = grant(readWrite, EXEC); // 7
console.log(readWrite, all, all.toString(2)); // 3 7 111
OR switches a bit on and leaves the others alone. Starting from 0 (no permissions), we grant READ, then WRITE, and get 3 (011). Granting EXEC as well gives 7 (111), with all three bits on.
Step 4: test a flag with AND
To ask "is WRITE on?", AND the permissions with the WRITE bit. Every other bit becomes 0, so the result is 0 if WRITE is off and not 0 if it is on.
const has = (perms, flag) => (perms & flag) !== 0;
console.log(has(readWrite, WRITE), has(readWrite, EXEC)); // true false
We compare with 0 on purpose. perms & flag is a number, like 2, not true. Writing !== 0 makes the check obvious to the next person reading your code.
Step 5: remove and toggle a flag
To switch one bit off, AND with the NOT of that flag. ~WRITE has every bit on except the WRITE bit, so ANDing with it clears that one bit and keeps the rest:
const revoke = (perms, flag) => perms & ~flag;
console.log(revoke(all, WRITE), revoke(all, WRITE).toString(2)); // 5 101
const toggle = (perms, flag) => perms ^ flag;
console.log(toggle(all, WRITE), toggle(toggle(all, WRITE), WRITE)); // 5 7
XOR toggles: it flips the flag's bit whatever it was. Toggling twice gets you back where you started.
Step 6: the XOR swap
Because XOR undoes itself, three XORs can swap two variables without a temporary one:
let a = 9;
let b = 4;
a ^= b;
b ^= a;
a ^= b;
console.log(a, b); // 4 9
It is a neat trick to understand, but don't use it in real code. A temporary variable, or [a, b] = [b, a], is clearer.
Step 7: & is not &&
They look alike, but they do different jobs:
console.log(5 & 3, 5 && 3); // 1 3
5 & 3 compares bits: 101 AND 011 is 001, which is 1. 5 && 3 is the logical "and": if the left side is truthy, it returns the right side, so it gives 3. Mixing them up is an easy typo, and both lines run without an error.
The full solution
The answer panel defines the three flags and the grant, has, revoke and toggle helpers, does the XOR swap, and prints the four operators on 12 and 10, the NOT cases, the permission values, the flag tests, the revoke, the swap and & against &&. Press Run to see the output.
const READ = 1;
const WRITE = 2;
const EXEC = 4;
const grant = (perms, flag) => perms | flag;
const has = (perms, flag) => (perms & flag) !== 0;
const revoke = (perms, flag) => perms & ~flag;
const toggle = (perms, flag) => perms ^ flag;
const readWrite = grant(grant(0, READ), WRITE); // 3
const all = grant(readWrite, EXEC); // 7
// XOR is its own inverse, which is what makes the swap work.
let a = 9;
let b = 4;
a ^= b;
b ^= a;
a ^= b;
console.log('12 & 10, 12 | 10, 12 ^ 10:', 12 & 10, 12 | 10, 12 ^ 10);
console.log('in binary :', (12 & 10).toString(2), (12 | 10).toString(2), (12 ^ 10).toString(2));
console.log('~12, ~0, ~-1 :', ~12, ~0, ~-1);
console.log('permissions :', readWrite, all, all.toString(2));
console.log('has WRITE, has EXEC :', has(readWrite, WRITE), has(readWrite, EXEC));
console.log('revoke WRITE from 7 :', revoke(all, WRITE));
console.log('swapped without a temp :', a, b);
console.log('5 & 3 against 5 && 3 :', 5 & 3, 5 && 3);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('12 & 10 is 8, 12 | 10 is 14, 12 ^ 10 is 6', [12 & 10, 12 | 10, 12 ^ 10], [8, 14, 6]);
test('~12 is -13, and ~x is always -x - 1', [~12, [0, 1, 12, -7].every((x) => ~x === -x - 1)], [-13, true]);
test('~0 is -1 and ~-1 is 0, so NOT is not a boolean flip', [~0, ~-1], [-1, 0]);
test('READ | WRITE is 3, and adding EXEC gives 7', [readWrite, all], [3, 7]);
test('& tests a flag, and only the flag asked about', [has(readWrite, WRITE), has(readWrite, EXEC)], [true, false]);
test('& ~flag clears one bit and leaves the rest', [revoke(all, WRITE), revoke(all, WRITE).toString(2)], [5, '101']);
test('^ toggles, so applying it twice returns the original', [toggle(all, WRITE), toggle(toggle(all, WRITE), WRITE)], [5, 7]);
test('three XORs swap two variables with no temporary', [a, b], [4, 9]);
test('and & is not &&: one is arithmetic, the other picks an operand', [5 & 3, 5 && 3], [1, 3]);
Do these on paper once. 12 is 1100 and 10 is 1010, so AND keeps 1000, OR gives 1110 and XOR gives 0110 — the bits that differ. NOT is the one that looks wrong: ~12 is -13, because the result is a signed 32-bit integer and flipping every bit of n gives -n - 1. There is no "bitwise not" that returns 243 unless you mask it back down with & 0xff.
Flags are where this pays off: one integer holds thirty-one independent booleans, | sets, & tests, & ~ clears and ^ toggles. Two cautions. & is not && — 5 & 3 is 1 while 5 && 3 is 3 — and (perms & flag) is a number, so compare it to 0 rather than trusting truthiness in code someone else will read. And the XOR swap is a party trick, not an optimisation: it is slower than a temporary on any modern engine, and it silently zeroes the variable if you pass the same one twice.
Common mistakes
- Expecting
~12to be 3. NOT flips all 32 bits, sign included, so the answer is -13. Mask it with~12 & 0b1111if you only want four bits. - Using flags that share bits. Flags must be 1, 2, 4, 8 and so on. A flag of 3 overlaps READ and WRITE.
- Typing
&when you meant&&.5 & 3is 1 and5 && 3is 3. Both run, so the mistake is silent.
Try it yourself
- Add a fourth flag,
DELETE = 8, grant it toall, and print the result in binary. - Write
listFlags(perms)that returns an array of the names of the flags that are on, such as['READ', 'EXEC']for 5. - Work out
~12 & 0b1111on paper, then check it in JavaScript.