Sitemap

Using bitfields in JavaScript for Simple Permission Systems

3 min readSep 1, 2016

Store a high number of boolean options as a single numeric value. This makes comparisons very easy & much faster than storing separate variables.

The bitwise AND operator (&)

The keystone to this arch lies in the bitwise & operator to determine if a bitfield value contains another flag.

Cited from the lovely article The Little Known Bitwise Operations and their Performance in JavaScript written by Rahul R:

a & b
Returns a one in each bit position for which the corresponding bits of both operands are ones.

So for example let’s say we want to build a simple permission system that allows, read, write, and admin access.

It could be represented in JS like the following:

const ACCESS = {
none: 0,
read: 2,
write: 4,
admin: 8,
owner: 16
};
let user = {};user.access = ACCESS.read + ACCESS.write + ACCESS.admin;if (user.access & ACCESS.owner) {
// Show site settings panel
}
if (user.access & ACCESS.admin) {
// Show admin features
}
if (user.access & ACCESS.read + ACCESS.write) {
// User has read & write access
}

First note that now all permissions can be accessible through a single bitfield value. In the example above user.access is 14. Which is represented as binary in the following Diagram A:

Diagram A

user.access & ACCESS.owner would fail because the binary representation of 14 contains no 16 bit values. So the binary AND (&) operator will return 0 which is falsey in JavaScript because the two numbers have no bit values in common as depicted by Diagram B below.

Diagram B

user.access & ACCESS.admin will pass because the value returned is 8. This is because the binary AND operator returns the bit values both operands share as seen in Diagram C below.

Diagram C

user.access & ACCESS.read + ACESS.write will also pass because the value returned is 6. This is because they both share the 4 bitvalue and the 2 bitvalue and the base-10 decimal representation of possessing both those bitvalues is 6 which is depicted below in Diagram D.

Diagram D

Now you can setup more complex permission systems by following this pattern and only requiring you to store it in a single integer.

--

--

No responses yet