Emmanuel Akinfulubi

JavaScriptBasic

Bit flags for permissions in JavaScript

Advanced · 4 min read

A user on a blog might be allowed to read, write, publish, or manage the whole site. You could store four separate true/false values. Or you can pack all four into a single number, one bit for each permission. File systems, game engines and network protocols do this a lot, because one number is small to store and fast to check.

In this tutorial you will hold four permissions in one integer and write helpers to test, grant, revoke and toggle them. You'll print the number in binary so you can see the bits, and learn the one trap that catches people: a bit test gives a number, not true. You need to know functions and numbers. Binary and the bitwise operators are explained from scratch.

Binary in one minute

Everyday numbers use ten digits. Binary uses two, 0 and 1, and each place is worth double the one to its right: 1, 2, 4, 8 and so on.

Output

binary 1011  =  8 + 0 + 2 + 1  =  11

Each 0 or 1 is a bit. Think of each bit as a switch: on or off. If each permission gets its own bit, one number can describe all four.

toString(2) writes a number in binary, and parseInt(text, 2) reads it back:

JavaScript

console.log((11).toString(2));    // 1011
console.log(parseInt('1011', 2)); // 11
console.log((3).toString(2).padStart(4, '0')); // 0011

padStart(4, '0') adds leading zeros so every number shows all four switches.

One power of two per permission

JavaScript

const READ = 1;      // 0001
const WRITE = 2;     // 0010
const PUBLISH = 4;   // 0100
const ADMIN = 8;     // 1000
console.log(READ + WRITE); // 3, which is 0011

The values are 1, 2, 4, 8, not 1, 2, 3, 4. Each power of two has exactly one bit on, so no two permissions share a bit. With 1, 2, 3, the value 3 would mean both "permission 3" and "permissions 1 and 2", and you couldn't tell them apart.

Here is the exercise. Try it on your own first if you like, or read on and we will build it together.

138 Permissions packed into one number

hard

Hold four permissions in a single integer, one bit each. Write the helpers to test, add, remove and toggle a permission, print the number in binary, and read a binary string back. Then show why if (flags & WRITE) is not the same as a boolean.

Stuck? Three hints, smallest first
  1. 1. Give each permission a distinct power of two, so no two share a bit.
  2. 2. | sets a bit, & tests it, & ~flag clears it, ^ flips it.
  3. 3. toString(2) writes binary and parseInt(text, 2) reads it, and both need padding to look right.

Step 1: grant with |

| is bitwise OR. It compares two numbers bit by bit, and a bit is on in the result if it's on in either number. That's exactly "add this permission":

Step 1

const READ = 1, WRITE = 2, ADMIN = 8;
const bits = (flags) => flags.toString(2).padStart(4, '0');
const grant = (flags, flag) => flags | flag;
const editor = grant(grant(0, READ), WRITE);
console.log(editor, bits(editor));                 // 3 0011
console.log(bits(grant(editor, ADMIN)));           // 1011
console.log(grant(editor, WRITE));                 // 3: already had it

Granting a permission the user already has changes nothing. With +, it would add 2 again and give 5, which means READ and PUBLISH. That's why we use |, not +.

Step 2: test with &

& is bitwise AND: a bit is on only if it's on in both numbers. Masking with one permission's bit leaves that bit if it's set, and 0 if it isn't:

Step 2

const READ = 1, WRITE = 2, PUBLISH = 4;
const editor = READ | WRITE;
console.log(editor & WRITE);   // 2
console.log(editor & PUBLISH); // 0
const has = (flags, flag) => (flags & flag) !== 0;
console.log(has(editor, WRITE), has(editor, PUBLISH)); // true false

Here's the trap. editor & WRITE is 2, not true. Inside an if that's fine, because 2 is truthy and 0 is falsy. But return it from a function, save it as JSON, or compare it with === true, and you have a number pretending to be a yes/no answer. !== 0 turns it into a real boolean.

Step 3: revoke with & ~, toggle with ^

~ is bitwise NOT: it flips every bit. So ~WRITE has every bit on except the WRITE bit. AND-ing with it keeps everything else and switches WRITE off:

Step 3

const READ = 1, WRITE = 2, ADMIN = 8;
const bits = (flags) => flags.toString(2).padStart(4, '0');
const revoke = (flags, flag) => flags & ~flag;
const toggle = (flags, flag) => flags ^ flag;
const editor = READ | WRITE;
console.log(bits(revoke(editor, WRITE)));            // 0001
console.log(revoke(editor, ADMIN));                  // 3: nothing to remove
console.log(bits(toggle(editor, ADMIN)));            // 1011
console.log(toggle(toggle(editor, ADMIN), ADMIN));   // 3: back where it started

^ is XOR ("exclusive or"): a bit is on if it's on in exactly one of the two numbers. Doing it with one flag flips that switch, so doing it twice flips it back.

Step 4: list the permissions by name

Step 4

const READ = 1, WRITE = 2, PUBLISH = 4, ADMIN = 8;
const NAMES = [[ADMIN, 'admin'], [PUBLISH, 'publish'], [WRITE, 'write'], [READ, 'read']];
const has = (flags, flag) => (flags & flag) !== 0;
const listOf = (flags) => NAMES.filter(([bit]) => has(flags, bit)).map(([, name]) => name);
console.log(listOf(READ | WRITE));  // [ 'write', 'read' ]
console.log(listOf(15));            // [ 'admin', 'publish', 'write', 'read' ]

NAMES pairs each bit with a label, listed from the highest bit down so the order matches the binary. filter keeps the pairs whose bit is set, and map pulls out the names. [, name] skips the first item of the pair and keeps the second.

15 is 1111: every switch on.

The 32-bit limit

The bitwise operators work on 32-bit whole numbers, and the top bit is used for the sign. So the 32nd flag would turn the number negative:

JavaScript

console.log((2 ** 31) | 0); // -2147483648

In practice that leaves room for 31 flags. If you need more, use a Set of names or BigInt. And be fair to the people reading your data: a packed number is compact but hard to read in a database. Plain named booleans are often the better choice unless you need the packing.

The full solution

The answer panel has the four flags and the helpers bits, has, grant, revoke, toggle and listOf. It prints an editor's permissions, then the same user promoted to publish. Press Run to see the output.

The answer

const READ = 1;      // 0001
const WRITE = 2;     // 0010
const PUBLISH = 4;   // 0100
const ADMIN = 8;     // 1000
const NAMES = [[ADMIN, 'admin'], [PUBLISH, 'publish'], [WRITE, 'write'], [READ, 'read']];

const bits = (flags) => flags.toString(2).padStart(4, '0');
const has = (flags, flag) => (flags & flag) !== 0;
const grant = (flags, flag) => flags | flag;
const revoke = (flags, flag) => flags & ~flag;
const toggle = (flags, flag) => flags ^ flag;
const listOf = (flags) => NAMES.filter(([bit]) => has(flags, bit)).map(([, name]) => name);

const editor = grant(grant(0, READ), WRITE);
console.log('editor is', editor, '=', bits(editor), listOf(editor));
console.log('promoted:', bits(grant(editor, PUBLISH)), listOf(grant(editor, PUBLISH)));

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.

9 checks

test('read plus write is 3, which is 0011', [editor, bits(editor)], [3, '0011']);
test('the bits it holds, named', listOf(editor), ['write', 'read']);
test('granting sets one bit and leaves the rest', [grant(editor, ADMIN), bits(grant(editor, ADMIN))], [11, '1011']);
test('revoking clears exactly one', [revoke(editor, WRITE), bits(revoke(editor, WRITE))], [1, '0001']);
test('revoking something not held changes nothing', revoke(editor, ADMIN), 3);
test('toggling twice is where you started', toggle(toggle(editor, ADMIN), ADMIN), 3);
test('a masked test returns the bit, not true', [editor & WRITE, editor & PUBLISH, has(editor, WRITE)], [2, 0, true]);
test('binary in and out, and 15 is all four', [parseInt('1011', 2), bits(15), listOf(15).length], [11, '1111', 4]);
test('but bitwise operators work on 32 bits, so a big flag wraps to negative', (2 ** 31) | 0, -2147483648);

One bit per permission is why the values are 1, 2, 4, 8 and not 1, 2, 3, 4. Powers of two never overlap, so READ | WRITE is 3 and can still be taken apart; with 1, 2, 3 the combination of the first two is the third and the information is gone. & ~flag for removal reads oddly at first: ~WRITE is a number with every bit set except that one, so the & keeps everything else and drops it.

The seventh assertion is the one that bites. editor & WRITE is 2, not true, and editor & PUBLISH is 0, not false. Inside an if that works by truthiness and reads fine, but returned from a function, stored in JSON, or compared with === true, it is a number pretending to be a boolean. Hence the explicit !== 0 in has.

The last assertion is the hard ceiling. Every bitwise operator converts its operands to signed 32-bit integers first, so bit 31 lands on the sign bit and bit 32 disappears entirely. Thirty-one flags is the practical limit; past that use BigInt, a Set of names, or several numbers. And be honest about the trade: a packed integer is compact and fast, and it is also unreadable in a database column, so most application code is better off with named booleans unless the packing is a protocol requirement.

Common mistakes

  • Numbering flags 1, 2, 3, 4. 3 is the same bits as 1 plus 2. Use powers of two.
  • Granting with +. Granting twice adds twice and switches on the wrong bit. Use |.
  • Returning flags & flag as a yes/no. It's a number. Compare with !== 0 to get a boolean.

Try it yourself

  1. Add a fifth permission, DELETE = 16, and print a user with all five as 11111.
  2. Write fromList(names) that turns ['read', 'publish'] back into the number 5.
  3. Write canEdit(flags) that is true when the user has WRITE or ADMIN, in a single & test.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.