Back to JavaScript
2025-12-278 min read

Bitwise (JavaScript)

Learn Bitwise (JavaScript) step by step with clear examples and exercises.

Why This Matters

Bitwise operations are a fundamental part of computer programming and play a crucial role in understanding how data is stored and manipulated at a low level. In JavaScript, mastering bitwise operations can help you:

  1. Write more efficient code by taking advantage of the faster execution times that bitwise operations offer compared to their logical or arithmetic counterparts.
  2. Understand the inner workings of computer systems, which is essential for working at a lower level in software development.
  3. Perform well in coding interviews and exams as knowledge of bitwise operations is often tested.
  4. Debug complex issues that involve bit manipulation, such as identifying specific flags or error codes within data structures.
  5. Work with binary data more effectively, which can be useful in various applications like network programming, image processing, and encryption/decryption.

Prerequisites

To fully grasp this lesson on bitwise operations in JavaScript, you should have a solid understanding of the following concepts:

  1. Basic JavaScript syntax and variables
  2. Arithmetic and logical operators
  3. Data types (numbers, strings, booleans)
  4. Control structures (if-else statements, loops, and conditional expressions)
  5. Understanding of signed and unsigned integers in JavaScript
  6. Familiarity with the concept of binary numbers and their representation

Core Concept

Bit Representation

In JavaScript, integers are represented using 32 bits. Each bit can have a value of either 0 or 1. When an integer is stored in memory, its binary representation is left-justified, with the most significant bit (MSB) on the left and the least significant bit (LSB) on the right.

For example, the decimal number 17 (base 10) can be represented as follows in binary:

17 = 00000000000000000000010001

Bitwise Operators

JavaScript provides several bitwise operators that allow you to manipulate individual bits within an integer:

  • Bitwise AND (&): Performs a bitwise AND operation on the corresponding bits of two operands. If both bits are 1, the result is 1; otherwise, the result is 0.
5 & 3 = 1
// binary: 00000101 & 00000011 = 00000001
  • Bitwise OR (|): Performs a bitwise OR operation on the corresponding bits of two operands. If either bit is 1, the result is 1; otherwise, the result is 0.
5 | 3 = 7
// binary: 00000101 | 00000011 = 00000111
  • Bitwise XOR (^): Performs a bitwise exclusive OR operation on the corresponding bits of two operands. If both bits are either both 0 or both 1, the result is 0; otherwise, the result is 1.
5 ^ 3 = 6
// binary: 00000101 ^ 00000011 = 00000110
  • Bitwise NOT (~): Flips all the bits of an operand.
~5 = -6
// binary: 11111010 (flip each bit) = 10000101
  • Bitwise left shift (<<): Shifts all the bits of an operand to the left by a specified number of positions. A zero is filled in on the rightmost side.
5 << 2 = 20
// binary: 00000101 (shifted left 2 places) = 10100000
  • Bitwise right shift (>>): Shifts all the bits of an operand to the right by a specified number of positions. The sign bit is filled in on the leftmost side for signed integers, and zero is filled in for unsigned integers.
5 >> 2 = 1
// binary: 00000101 (shifted right 2 places) = 00000001

Bitwise Operators with Numbers and Strings

When performing bitwise operations with numbers, JavaScript automatically converts non-integer values to integers. However, when performing bitwise operations with strings, JavaScript treats each character as a separate ASCII value and performs the operation on the corresponding bits of the ASCII codes.

"A" & "B" = 65 & 66 = 01000001 & 01000010 = 00000000 (both characters are shifted to the left until their least significant bits align, and then ANDed)

Right-Shift Operator with Signed Integers

When using the right-shift operator (>>) with signed integers, JavaScript fills in the leftmost bit based on the sign of the number:

  • If the number is positive, the leftmost bit is filled with 0.
  • If the number is negative, the leftmost bit is filled with 1.

This behavior can be used to extract the sign of a signed integer by performing a right shift and checking the resulting value:

let num = -5;
let sign = (num >> 31) & 1; // sets sign to either 0 or 1, depending on whether the number is positive or negative

Bitwise Operators and Overflow

Note that that JavaScript does not support unsigned integers natively. This means that when performing bitwise operations with large numbers, you may encounter overflow issues. To avoid these problems, it's recommended to use libraries like BigInt or BigNumber.js.

Worked Example

Let's create a function that swaps two variables without using a temporary variable:

function swap(a, b) {
let x = a ^ b;
a = a ^ b;
b = x ^ a;
return [a, b];
}

let x = 5;
let y = 3;
console.log(swap(x, y)); // Output: [3, 5]

In this example, we use the XOR operator to create a temporary value that contains the bitwise exclusive OR of a and b. Then, we perform two more XOR operations to swap the values of a and b without using a temporary variable.

Common Mistakes

  1. Forgetting about signed integers: When performing right shifts with signed integers, be aware that JavaScript fills in the leftmost bit based on the sign of the number. This can lead to unexpected results if you're not careful.
  2. Mixing numbers and strings: Be cautious when using bitwise operators with both numbers and strings, as the behavior can be unintuitive.
  3. Ignoring the order of operations: Remember that JavaScript follows standard operator precedence rules, which may lead to unexpected results if you're not careful about grouping expressions or using parentheses.
  4. Using bitwise operators inappropriately: Bitwise operators are powerful tools, but they should be used judiciously and only when necessary for performance reasons or to solve specific problems that require manipulating individual bits.
  5. Not considering overflow issues: When working with large numbers, it's important to use libraries like BigInt or BigNumber.js to avoid overflow issues.
  6. Forgetting about the sign bit when using right shift operator: Be aware that the leftmost bit filled in during a right shift operation depends on the sign of the number.
  7. Not understanding the difference between logical AND and bitwise AND: Logical AND compares two Boolean values, while bitwise AND operates on individual bits within integers.
  8. Misusing the XOR operator for logical exclusion: The XOR operator is not a suitable replacement for logical NOT (!) in all cases. Use it carefully and only when necessary.

Practice Questions

  1. Write a function that checks if a number is even using bitwise operations.
  2. Write a function that reverses the order of the digits in an integer using bitwise operations.
  3. Write a function that counts the number of set bits (bits with a value of 1) in an integer using bitwise operations.
  4. Write a function that calculates the maximum and minimum values that can be represented by a given number of bits using bitwise operations.
  5. Write a function that checks if two integers have any common set bits using bitwise operations.
  6. Write a function that finds the first set bit (from right to left) in an integer using bitwise operations.
  7. Write a function that rotates an integer to the left by a specified number of positions using bitwise operations.
  8. Write a function that rotates an integer to the right by a specified number of positions using bitwise operations.
  9. Write a function that finds the least common multiple (LCM) and greatest common divisor (GCD) of two integers using bitwise operations.
  10. Write a function that calculates Fibonacci numbers using bitwise operations.

FAQ

  1. Why do we need to care about bitwise operators when JavaScript automatically converts non-integer values to integers? While JavaScript does automatically convert non-integer values to integers, this conversion may result in unexpected behavior or performance issues, especially when dealing with large numbers or performing complex operations. Bitwise operators can help you avoid these problems by allowing you to manipulate individual bits directly.
  2. What's the difference between bitwise AND and logical AND? The main difference is that bitwise AND operates on individual bits within integers, while logical AND compares two Boolean values. For example:
// Bitwise AND:
5 & 3 = 1
// binary: 00000101 & 00000011 = 00000001

// Logical AND:
5 && 3 = true (both values are non-zero, so the result is true)
  1. Why does JavaScript fill in the leftmost bit when performing a right shift with signed integers? This behavior allows JavaScript to maintain the sign of a number during a right shift. For example, if we perform a right shift on the negative number -5:
-5 >> 1 = -2 (binary: 10000101 shifted right 1 place = 10000010)

In this case, shifting the number one place to the right preserves its negative sign. If JavaScript didn't fill in the leftmost bit based on the sign of the number, we would lose this information during the shift operation.

  1. Why does JavaScript not support unsigned integers natively? JavaScript was designed primarily for web development and did not originally include support for unsigned integers due to the limited need for them in that context. However, libraries like BigInt or BigNumber.js can be used to work with large unsigned integers when necessary.
  2. What is the difference between the bitwise OR (|) and the logical OR (||)? The main difference is that bitwise OR operates on individual bits within integers, while logical OR compares two Boolean values. For example:
// Bitwise OR:
5 | 3 = 7
// binary: 00000101 | 00000011 = 00000111

// Logical OR:
5 || 3 = true (either value is non-zero, so the result is true)
  1. What is the difference between the bitwise XOR (^) and the logical XOR (^=)? The main difference is that bitwise XOR operates on individual bits within integers, while logical XOR updates a variable by performing an exclusive OR operation with another value. For example:
// Bitwise XOR:
5 ^ 3 = 6
// binary: 00000101 ^ 00000011 = 00000110

// Logical XOR (assuming `a` is initially 5 and `b` is initially 3):
let a = 5;
let b = 3;
a ^= b; // now `a` is 6
Bitwise (JavaScript) | JavaScript | XQA Learn