Exponentiation Bitwise and Shift Operators in JavaScript
The exponent operator groups from the right, and bitwise and shift operators work on 32-bit integers. See bit flags, masks, tricks and overflow limits.

Bit operations look like a relic of C, and they are alive in JavaScript wherever data is packed tightly: permission flags, color channels, hash functions, binary file formats and feature switches. They also behave differently from the arithmetic around them, because every one of them first squeezes its operands into 32-bit integers. That conversion is the source of nearly every surprise, and it is easier to see than to describe. This post covers the exponent operator, the bitwise operators and the shifts with output from Node.js 24 as an ES module, then builds a small flag system, lists the idioms that people use and the ones that break, and shows when bigint is the right answer. The 32-bit conversion follows from how numbers work in JavaScript, and the precedence traps with bitwise operators are in the post on operator precedence.
The exponent operator
** raises the left operand to the power of the right, and groups from the right.
console.log(2 ** 10, 2 ** -1, 2 ** 0.5);
console.log(2 ** 3 ** 2, (2 ** 3) ** 2);
console.log((-2) ** 2, (-2) ** 3, -(2 ** 2));
console.log(10 ** 21, 10 ** 22, 2 ** 53, 2 ** 1024);
console.log(2n ** 100n, 7n ** 2n);
let growth = 3;
growth **= 4;
console.log(growth, Math.pow(2, 8) === 2 ** 8);
try {
console.log(2n ** 2);
} catch (error) {
console.log(error.name + ": " + error.message);
}1024 0.5 1.4142135623730951
512 64
4 -8 -4
1e+21 1e+22 9007199254740992 Infinity
1267650600228229401496703205376n 49n
81 true
TypeError: Cannot mix BigInt and other types, use explicit conversionsThe right-to-left grouping made 2 ** 3 ** 2 equal 512. A negative base needs parentheses, since -2 ** 2 is a syntax error, and bigint powers are exact, with no mixing with numbers. 2 ** 1024 overflows to Infinity, the double's limit. The operator is the same as Math.pow(), and reads better.
Bitwise operators work on 32 bits
Each bitwise operator converts both operands to signed 32-bit integers, which drops any fraction and wraps values beyond the range.
const bits = (n) => (n >>> 0).toString(2).padStart(8, "0");
console.log(bits(0b1100 & 0b1010), bits(0b1100 | 0b1010), bits(0b1100 ^ 0b1010));
console.log(~5, ~-1, ~0, ~~4.9, ~~-4.9);
console.log(5.9 | 0, -5.9 | 0, 2 ** 31 | 0, 2 ** 32 | 0, (2 ** 32 + 5) | 0);
console.log(0xffffffff | 0, 0xffffffff >>> 0, -1 >>> 0, -1 >>> 31);
console.log(1 << 3, -16 >> 2, -16 >>> 28, 1 << 31, 1 << 32, 1 << 33);
console.log(NaN | 0, Infinity | 0, "12" | 0, null | 0, undefined | 0);00001000 00001110 00000110
-6 0 -1 4 -4
5 -5 -2147483648 0 5
-1 4294967295 4294967295 1
8 -4 15 -2147483648 1 2
0 0 12 0 0&, | and ^ combined bits as expected. ~ flips every bit of a 32-bit value, so ~5 is -6, and ~~x flips twice to truncate a fraction toward zero. Fractions were dropped, 2 ** 31 wrapped to a negative number and 2 ** 32 wrapped to zero. The unsigned right shift >>> 0 reinterprets the bits as unsigned, which is how -1 becomes 4294967295. Shift counts are taken modulo 32, so 1 << 32 is 1, not 4,294,967,296. And non-numbers convert first: NaN, Infinity and null become 0, and the string "12" becomes 12.
Flags and masks
The practical use is a set of yes-or-no options packed into one integer. Each flag is one bit, so the whole set fits in a number and can be stored, compared and sent as a single value.
const Permission = Object.freeze({
READ: 1 << 0,
WRITE: 1 << 1,
DELETE: 1 << 2,
ADMIN: 1 << 3,
});
const has = (flags, flag) => (flags & flag) !== 0;
const add = (flags, flag) => flags | flag;
const remove = (flags, flag) => flags & ~flag;
const toggle = (flags, flag) => flags ^ flag;
const names = (flags) => Object.keys(Permission).filter((name) => has(flags, Permission[name]));
let user = Permission.READ | Permission.WRITE;
console.log(user, names(user));
user = add(user, Permission.DELETE);
console.log(user.toString(2).padStart(4, "0"), names(user));
user = remove(user, Permission.WRITE);
console.log(names(user), has(user, Permission.WRITE));
user = toggle(toggle(user, Permission.ADMIN), Permission.ADMIN);
console.log(user, has(user, Permission.READ | Permission.DELETE));3 [ 'READ', 'WRITE' ]
0111 [ 'READ', 'WRITE', 'DELETE' ]
[ 'READ', 'DELETE' ] false
5 trueEach flag was a distinct power of two, built with a left shift so the intent is visible. | added a flag, & ~flag cleared it, ^ toggled it and & tested it. Notice the parentheses in has: flags & flag !== 0 would group the comparison first and give the wrong answer, a trap covered in the precedence post. The set READ | DELETE was tested by checking that all its bits are present, which (flags & mask) === mask does more precisely than !== 0, since the latter is true if any bit is present.
The packed form has a limit of 31 usable flags in a signed 32-bit value, and for more, use bigint or an array of integers.
const mask = 0b0101;
console.log((0b0111 & mask) !== 0, (0b0010 & mask) !== 0);
console.log((0b0111 & mask) === mask, (0b0100 & mask) === mask);
let wide = 0n;
for (const index of [3, 40, 64]) wide |= 1n << BigInt(index);
console.log(wide.toString(2).length, (wide >> 40n) & 1n, (wide >> 41n) & 1n);true false
true false
65 1n 0nThe first line tests "any of" and the second tests "all of". The bigint version held flags at positions 3, 40 and 64, far beyond the 32-bit limit, with the same operators, and shifts take a bigint count.
Common idioms and their limits
A few bit tricks are everywhere, and each has a range where it works.
const isPowerOfTwo = (n) => n > 0 && (n & (n - 1)) === 0;
console.log([1, 2, 3, 4, 6, 8, 1024, 1000].map(isPowerOfTwo));
const isEven = (n) => (n & 1) === 0;
console.log(isEven(10), isEven(7), isEven(-3));
const popcount = (n) => {
let count = 0;
for (let v = n >>> 0; v; v &= v - 1) count += 1;
return count;
};
console.log(popcount(0b1011), popcount(255), popcount(-1));
console.log(Math.clz32(1), Math.clz32(0), 31 - Math.clz32(1024));
let a = 5;
let b = 9;
a ^= b;
b ^= a;
a ^= b;
console.log(a, b);
console.log(Math.trunc(2 ** 32 + 5.7), (2 ** 32 + 5.7) | 0, ~~(2 ** 32 + 5.7));
console.log(Math.floor(-4.5), ~~-4.5, -4.5 | 0);[
true, true,
false, true,
false, true,
true, false
]
true false false
3 8 32
31 32 10
9 5
4294967301 5 5
-5 -4 -4The power-of-two test works because a power of two has one bit set, so n & (n - 1) clears it to zero. Parity with & 1 works for negative numbers too. The population count loop removes the lowest set bit each time, and Math.clz32 counts leading zeros, which gives the position of the highest bit and so the base-2 logarithm for powers of two. The XOR swap works for integers and has no advantage over a destructuring swap. The last two lines show the limits of the truncation tricks: | 0 and ~~ wrap numbers above 2^31 and give wrong answers, and they truncate toward zero while Math.floor rounds down, so negative fractions differ. Use Math.trunc() when the value may be large.
Packing and unpacking values
Bit shifts pack several small values into one integer and unpack them again, which is how a color or a version is stored in a single number.
const pack = (r, g, b) => ((r & 255) << 16) | ((g & 255) << 8) | (b & 255);
const unpack = (rgb) => [(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255];
const orange = pack(255, 165, 0);
console.log(orange, "#" + orange.toString(16).padStart(6, "0"));
console.log(unpack(orange), unpack(0x1e90ff));
const version = (major, minor, patch) => (major << 20) | (minor << 10) | patch;
const v = version(24, 11, 1);
console.log(v, v >> 20, (v >> 10) & 1023, v & 1023);
console.log(version(24, 0, 0) > version(22, 12, 5));16753920 #ffa500
[ 255, 165, 0 ] [ 30, 144, 255 ]
25177089 24 11 1
trueThree channels went into one number and came back out with a shift and a mask. The version example packs three fields so that a plain numeric comparison orders versions correctly, since the major sits in the high bits. Always mask the extracted field, because the shift leaves the higher fields in place. For alpha channels near the top bit, remember the signed result: 0xff000000 | 0 is negative, and >>> 0 makes it positive.
Hashing with Math.imul
Hash functions multiply and mix bits, and a plain * goes wrong because the product of two 32-bit numbers can exceed 2^53 and lose low bits before any masking happens. Math.imul() multiplies as 32-bit integers and returns the low 32 bits exactly, which is what hash algorithms need.
function fnv1a32(text) {
let hash = 0x811c9dc5;
for (const byte of new TextEncoder().encode(text)) {
hash ^= byte;
hash = Math.imul(hash, 0x01000193);
}
return hash >>> 0;
}
console.log(fnv1a32("hello").toString(16));
console.log(fnv1a32("").toString(16));
const wrong = (0x811c9dc5 ^ 104) * 0x01000193;
console.log(Number.isSafeInteger(wrong), (wrong | 0) === Math.imul(0x811c9dc5 ^ 104, 0x01000193));
console.log(Math.imul(0xffffffff, 5), Math.imul(2 ** 16, 2 ** 16));4f9f2cab
811c9dc5
false false
-5 0The first line is the 32-bit FNV-1a hash of "hello". The product in wrong is not a safe integer, so masking it afterward gives a different answer from Math.imul, which the comparison shows. The >>> 0 at the end turns the signed result into the unsigned value that the algorithm defines, and Math.imul(0xffffffff, 5) shows wraparound that matches C's int32 multiplication. For anything stronger than a quick bucket hash, such as passwords or integrity checks, use the crypto module, and do not write your own.
Where bit tricks stop being the right tool
Bitwise code is compact and hard to read. Use it for flags, binary formats and hash functions, and write arithmetic for arithmetic. Do not use | 0 to round, ~~ to floor or << 1 to double, in application code: each is correct only in a narrow range and obscure to the next reader, and modern engines optimize plain arithmetic well. Do not use bit operations on values that may exceed 2^31, such as timestamps in milliseconds, which are about 2^41, since they wrap silently. And do not store more than 31 flags in a number, so reach for bigint, a Set of names or a typed array.
When you do use flags, put the constants in one module, name them for what they mean, and write the has, add and remove helpers once, so no caller writes a raw & or ~ and the precedence trap cannot recur. For performance claims, measure on your engine and your data. We have not found a case in ordinary application code where a bit trick beat the plain version by enough to justify the clarity lost.
The operators are defined in the specification under bitwise shift operators and binary bitwise operators, and MDN's pages on bitwise operators and exponentiation cover each one.


