JavaScript Bitwise Operators: AND, OR, XOR, NOT, Shifts and Bit Flags
How &, |, ^, ~, <<, >> and >>> work on 32-bit integers, why 2 ** 31 | 0 is negative, the x | 0 truncation trick and its limits, permission flags and bit masks, packing colors, classic interview bit tricks, and bitwise operators on BigInt.
kvi5hnuCode Sprout team member8 min readOn this page
Bitwise operators work on the individual bits (binary digits) of numbers. You won't need them in most application code, but they show up in permission flags, graphics and color math, hashing, binary file formats, WebGL, performance-sensitive libraries and, very reliably, in coding interviews. They're also behind a few idioms you'll see in other people's code, such as x | 0.
| Operator | Name | Example | Result |
|---|---|---|---|
a & b | AND | 0b1100 & 0b1010 | 0b1000 (8) |
a | b | OR | 0b1100 | 0b1010 | 0b1110 (14) |
a ^ b | XOR (exclusive or) | 0b1100 ^ 0b1010 | 0b0110 (6) |
~a | NOT | ~5 | -6 |
a << n | left shift | 1 << 3 | 8 |
a >> n | sign-propagating right shift | -16 >> 2 | -4 |
a >>> n | zero-fill right shift | -16 >>> 2 | 1073741820 |
The 32-bit conversion
JavaScript numbers are 64-bit floating point, but the bitwise operators pretend they're 32-bit signed integers. Before operating, each operand is converted:
- Convert to a number (
"12"becomes 12;NaNand±Infinitybecome 0). - Drop the fractional part (toward zero).
- Keep only the lowest 32 bits, and read them as a signed integer in two's complement, where the top bit means negative.
The result is a 32-bit integer again (except for >>>, which gives an unsigned one). The conversion explains every strange result in this article:
console.log(3.7 | 0, -3.7 | 0, "12" | 0);
console.log(NaN | 0, Infinity | 0);
console.log(2 ** 31 | 0, 2 ** 32 + 5 | 0);
console.log(5e9 | 0);
3 -3 12
0 0
-2147483648 5
705032704
2 ** 31 has only its top (32nd) bit set, which in two's complement means −2,147,483,648. 2 ** 32 + 5 loses everything above bit 31, leaving 5. And 5 billion, which doesn't fit in 32 bits, comes out as a meaningless number.
Two's complement in one paragraph
In 32-bit two's complement, the highest bit has the value −2³¹ instead of +2³¹. So 0...0001 is 1, and 1...1111 (all 32 bits set) is −1. To negate a number, flip all its bits and add 1. That's why ~x (flip all bits) equals -x - 1: ~5 is −6 and ~-1 is 0.
To see the bits, use toString(2), and for negative numbers >>> 0 first, which reinterprets them as unsigned:
console.log((11).toString(2).padStart(8, "0"));
console.log((-1 >>> 0).toString(2));
console.log((-1 >>> 0).toString(16), Number.parseInt("1011", 2));
00001011
11111111111111111111111111111111
ffffffff 11
AND, OR, XOR and NOT
The first three combine two numbers bit by bit: each column of bits is processed on its own.
&(AND) gives 1 where both bits are 1.|(OR) gives 1 where either bit is 1.^(XOR) gives 1 where exactly one bit is 1.~(NOT) flips every bit of a single operand.

const a = 0b11001010; // 202
const b = 0b10100110; // 166
console.log(a & b, a | b, a ^ b);
console.log(~a, ~~a);
130 238 108
-203 202
Bit flags: many booleans in one number
The most practical use of bitwise operators is storing several on/off settings in one integer. Give each flag its own bit, using a power of two:
const READ = 1 << 0; // 0b001 = 1
const WRITE = 1 << 1; // 0b010 = 2
const EXEC = 1 << 2; // 0b100 = 4
let perms = READ | WRITE; // combine flags
console.log(perms, (perms & WRITE) !== 0, (perms & EXEC) !== 0);
perms |= EXEC; // turn on
perms &= ~WRITE; // turn off: AND with every bit except WRITE
perms ^= READ; // toggle
console.log(perms.toString(2));
3 true false
100
This is how Unix file permissions (chmod 755), WebGL options like COLOR_BUFFER_BIT | DEPTH_BUFFER_BIT, Node's fs.constants and many binary protocols work. One 32-bit number holds up to 32 flags, and checking several at once is a single operation: (perms & (READ | WRITE)) === (READ | WRITE).
In ordinary application code, an object ({ read: true, write: false }) or a Set of strings is usually more readable. Use flags when you need compactness, need to match an external format, or are working in a hot path.
Shift operators
Shifts move all bits left or right by a number of positions:
a << nmoves bits left, filling with zeros. Each step doubles the value, as long as nothing reaches the sign bit.a >> nmoves bits right, copying the sign bit into the new positions, so negative numbers stay negative. Each step halves, rounding toward negative infinity.a >>> nmoves bits right, filling with zeros. The result is always non-negative, interpreted as unsigned.
console.log(1 << 3, 5 << 1, 1 << 31);
console.log(7 >> 1, -7 >> 1, -16 >> 2, -16 >>> 2);
console.log(1 << 32, 1 << 33); // the shift count uses only its low 5 bits
8 10 -2147483648
3 -4 -4 1073741820
1 2
Two gotchas from this output:
-7 >> 1is −4, not −3:>>rounds down, whileMath.trunc(-7 / 2)rounds toward zero.- The shift count is taken modulo 32, so
1 << 32is 1, not 0. Shifting by 32 or more doesn't clear the number.
Packing and unpacking values
Shifts plus masks let you pack several small numbers into one. A 24-bit RGB color is the classic example:
const color = 0x3a7bd5;
const red = (color >> 16) & 0xff; // shift the red byte down, mask the rest away
const green = (color >> 8) & 0xff;
const blue = color & 0xff;
console.log(red, green, blue);
const packed = (red << 16) | (green << 8) | blue;
console.log(packed.toString(16));
58 123 213
3a7bd5
0xff is a mask: eight 1 bits that keep the lowest byte and zero everything else.
The | 0 and ~~ truncation tricks
Because every bitwise operation converts to a 32-bit integer, x | 0 and ~~x truncate a number toward zero. You'll see them in older code and in code written for asm.js-style performance:
console.log(~~3.7, ~~-3.7, 3.7 | 0);
console.log(Math.trunc(5e9 + 0.5), (5e9 + 0.5) | 0); // beyond 32 bits: garbage
3 -3 3
5000000000 705032704
They're only correct for values within the 32-bit signed range (about ±2.1 billion). Timestamps in milliseconds (about 1.8 trillion in 2026), file sizes and IDs easily exceed that. Use Math.trunc in modern code: it's clear, correct for every number, and just as fast in current engines.
Another old idiom: ~str.indexOf(x) is truthy when indexOf finds something, because ~-1 is 0. Use str.includes(x) instead.
Classic interview bit tricks
These come up in algorithm interviews and competitive programming:
const isPowerOfTwo = (n) => n > 0 && (n & (n - 1)) === 0;
console.log(isPowerOfTwo(64), isPowerOfTwo(96));
const countBits = (n) => { // Kernighan: n & (n - 1) clears the lowest set bit
let count = 0;
while (n) { n &= n - 1; count++; }
return count;
};
console.log(countBits(0b1011011));
let x = 5, y = 9; // XOR swap (a curiosity: use [x, y] = [y, x])
x ^= y; y ^= x; x ^= y;
console.log(x, y);
const findUnique = (nums) => nums.reduce((acc, n) => acc ^ n, 0); // pairs cancel out
console.log(findUnique([4, 7, 2, 7, 4]));
console.log((13 & 1) === 1 ? "odd" : "even");
true false
5
9 5
2
odd
The findUnique trick works because n ^ n is 0 and n ^ 0 is n, so every number that appears twice cancels itself out. Math.clz32(n) (count leading zero bits) and Math.imul(a, b) (32-bit integer multiplication) are related built-ins used in hashing code.
Bitwise operators with BigInt
All bitwise operators except >>> work on BigInt (article 13), and with BigInt there's no 32-bit limit: values behave like two's complement numbers of unlimited width.
console.log(5n & 3n, ~5n, 1n << 70n, -8n >> 1n);
for (const code of ["1n >>> 1n", "5n | 1"]) {
try { eval(code); } catch (err) { console.log(code.padEnd(9), err.name); }
}
1n -6n 1180591620717411303424n -4n
1n >>> 1n TypeError
5n | 1 TypeError
>>> doesn't exist for BigInt because "fill with zeros from the left" has no meaning for a number with no fixed width. As always with BigInt, you can't mix it with regular numbers. BigInt is the right tool for 64-bit IDs and flags that don't fit in 32 bits.
Common questions
Why does ~5 give −6 and not something like 250?
Bitwise operators work on 32-bit signed integers. Flipping all 32 bits of 5 (0...0101) gives 1...1010, which two's complement reads as −6. To see the unsigned value, use ~5 >>> 0 (4294967290).
Are bitwise operators faster than arithmetic in JavaScript?
Not in any way you should rely on. Modern engines optimize Math.trunc, * 2 and % 2 very well. Use bitwise operators when the problem is about bits, not as a micro-optimization, since they silently break outside the 32-bit range.
How do I store more than 32 flags?
Use BigInt (1n << 40n), several numbers, or a typed array as a bitset (part 11). For non-performance code, a Set of flag names is simplest.
Does x >> 0 round the same way as x | 0?
Yes: both convert to a 32-bit integer, truncating toward zero. The difference between >> and division shows up only when you shift by one or more positions: -7 >> 1 is −4 while Math.trunc(-7 / 2) is −3.
Summary
- Bitwise operators convert operands to 32-bit signed integers (fractions dropped, high bits lost,
NaNandInfinity→ 0). &,|,^combine bits column by column;~xequals-x - 1.<<shifts left,>>shifts right keeping the sign (rounding down),>>>shifts right filling zeros (unsigned result); shift counts are taken modulo 32.- Flags: define powers of two, combine with
|, test with&, clear with& ~flag, toggle with^. x | 0and~~xonly truncate correctly inside ±2³¹; useMath.trunc.- BigInt supports all bitwise operators except
>>>, without the 32-bit limit.
Practice Questions
What is 0b1010 ^ 0b0110, and what does x ^ x always give?
Answer
0b1100, which is 12. x ^ x is always 0, since every bit matches itself.
A style is stored as bit flags, like this. How do you test whether italic is on, and how do you turn bold off?
const BOLD = 1, ITALIC = 2, UNDERLINE = 4;
let style = BOLD | UNDERLINE;
Answer
Test: (style & ITALIC) !== 0, which is false here. Turn bold off: style &= ~BOLD;, leaving UNDERLINE (4).
Why does Date.now() | 0 give a wrong, possibly negative number?
Answer
Date.now() is about 1.8 × 10¹², far above the 32-bit range, so | 0 keeps only the low 32 bits and reads them as signed. Use Math.trunc (or nothing at all, since Date.now() is already an integer).
What do -1 >> 28 and -1 >>> 28 return?
Answer
-1 and 15. >> copies the sign bit, so all 1 bits stay all 1 bits (−1). >>> fills with zeros, leaving the top four bits of the original: 0b1111 = 15.
Extract the green channel from the color 0x00ff8800.
Answer
(0x00ff8800 >> 8) & 0xff is 0x88, which is 136. The shift moves the green byte to the bottom, and the mask removes the red byte above it.
Previous: JavaScript Arithmetic Operators: +, -, *, /, %, **, Increment and Decrement
Next: JavaScript Comparison Operators: <, >, String Ordering, in and instanceof

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.