javascript

Bitwise OR (|)

Learn the JavaScript bitwise OR operator (|). Understand how it works with binary numbers, how to combine flags, and its practical uses in coding.

11 min read 8 sections Tutorial
Share

The bitwise OR operator, written as `|`, is a special tool in JavaScript. It works directly with the binary (base-2) representation of numbers. You will learn how it combines bits, how to use it for setting flags, and why it is important for certain programming tasks.

Bitwise OR (|)

Bitwise OR (|)

The bitwise OR operator, written as |, is a special tool in JavaScript. It works directly with the binary (base-2) representation of numbers. You will learn how it combines bits, how to use it for setting flags, and why it is important for certain programming tasks.

What is Bitwise OR?

The bitwise OR operator (|) compares each bit position of two numbers. If at least one of the bits is a 1, the resulting bit is 1. Otherwise, if both bits are 0, the resulting bit is 0.

Binary Logic

Understand how the OR operator works on individual 0s and 1s in binary numbers.

Setting Flags

Learn to combine multiple options or permissions into a single number using bitwise OR.

Efficient Storage

See how bitwise operations can save memory by packing several true/false values into one variable.

Real-World Uses

Discover practical applications in game development, device drivers, and configuration settings.

Understanding the Bitwise OR Operator

Getting Started

Understanding the Bitwise OR Operator

Computers store all numbers as binary digits, which are 0s and 1s. The bitwise OR operator looks at these 0s and 1s, one by one. It compares the bits at the same position in two different numbers. If either bit is a 1, the result for that position is 1. If both bits are 0, the result is 0.

javascript
1let num1 = 5; // Binary: 0101
2let num2 = 3; // Binary: 0011
3
4// Perform bitwise OR operation
5let result = num1 | num2;
6
7console.log(result); // This will output 7 (Binary: 0111)
8
9/*
10 How it works:
11 num1: 0101 (decimal 5)
12 num2: 0011 (decimal 3)
13 ------
14 OR: 0111 (decimal 7)
15
16 - First bit (rightmost): 1 OR 1 = 1
17 - Second bit: 0 OR 1 = 1
18 - Third bit: 1 OR 0 = 1
19 - Fourth bit: 0 OR 0 = 0
20*/

Don't Confuse with Logical OR (||)

The bitwise OR operator (|) is different from the logical OR operator (||). Logical OR works with true/false values and short-circuits. Bitwise OR always converts numbers to binary and compares every single bit, returning a new number. Using || when you mean | is a common beginner mistake.

How Bitwise OR Combines Numbers

How Bitwise OR Combines Numbers

When you use the bitwise OR operator, JavaScript first changes your decimal numbers into their binary form. Then, it compares each pair of bits. The result is a new binary number, which JavaScript then converts back to a decimal number for you. This process is very fast because it is how computers naturally handle numbers.

javascript
1let settingA = 8; // Binary: 1000
2let settingB = 4; // Binary: 0100
3let settingC = 1; // Binary: 0001
4
5// Combine settingA and settingB
6let combinedAB = settingA | settingB; // 1000 | 0100 = 1100 (decimal 12)
7console.log(`Combined A and B: ${combinedAB}`); // Outputs: 12
8
9// Combine all three settings
10let combinedABC = settingA | settingB | settingC; // 1000 | 0100 | 0001 = 1101 (decimal 13)
11console.log(`Combined A, B, and C: ${combinedABC}`); // Outputs: 13
12
13/*
14 Step-by-step for combinedABC:
15 settingA: 1000
16 settingB: 0100
17 settingC: 0001
18 ----------
19 Result: 1101 (decimal 13)
20
21 Notice how each '1' from any of the original numbers makes a '1' in the final result.
22*/
✗ BadWrong (Using Addition for Flags)
const READ_PERMISSION = 1;
const WRITE_PERMISSION = 2;
const EXECUTE_PERMISSION = 4;
// This adds the numbers, but doesn't correctly represent combined flags
let userPermissions = READ_PERMISSION + WRITE_PERMISSION;
// userPermissions is 3. If you add EXECUTE (4), it becomes 7.
// This works for simple cases but can lead to issues
// if flags are not powers of 2 or if you need to remove a flag.
console.log(userPermissions); // Outputs: 3
✓ GoodCorrect (Using Bitwise OR for Flags)
const READ_PERMISSION = 1; // Binary: 001
const WRITE_PERMISSION = 2; // Binary: 010
const EXECUTE_PERMISSION = 4; // Binary: 100
// This correctly combines flags using their distinct bit positions
let userPermissions = READ_PERMISSION | WRITE_PERMISSION;
// userPermissions is 3 (Binary: 011).
// Each '1' sets a specific permission.
console.log(userPermissions); // Outputs: 3
// To add another permission:
userPermissions = userPermissions | EXECUTE_PERMISSION;
console.log(userPermissions); // Outputs: 7 (Binary: 111)
// This is how you reliably combine unique options.

Bitwise OR for Setting Flags

Bitwise OR for Setting Flags

One of the most powerful uses of bitwise OR is for 'flags'. Flags are like switches that can be on or off. Each flag is given a unique power-of-2 number (1, 2, 4, 8, etc.). This makes sure each flag uses a different bit position. You can combine many flags into one number using bitwise OR, and then easily check which flags are set.

Using Booleans for Multiple Options
let canRead = true;
let canWrite = false;
let canDelete = true;
function checkAccess(read, write, del) {
if (read) {
console.log("User can read.");
}
if (write) {
console.log("User can write.");
}
if (del) {
console.log("User can delete.");
}
}
checkAccess(canRead, canWrite, canDelete);
VS
Using Bitwise OR for Flags
const PERM_READ = 1; // Binary: 001
const PERM_WRITE = 2; // Binary: 010
const PERM_DELETE = 4; // Binary: 100
// Combine permissions into a single number
let userPermissions = PERM_READ | PERM_DELETE;
// userPermissions is now 5 (Binary: 101)
function checkAccess(permissions) {
if (permissions & PERM_READ) {
console.log("User can read.");
}
if (permissions & PERM_WRITE) {
console.log("User can write.");
}
if (permissions & PERM_DELETE) {
console.log("User can delete.");
}
}
checkAccess(userPermissions);

When to Prefer Bitwise Flags

Use bitwise flags when you have many independent true/false options that need to be stored or passed around as a single value. This is very common in system settings, permissions, or game states. It makes your code more compact and often more efficient than using many separate boolean variables.

Practical Uses of Bitwise OR

Practical Uses of Bitwise OR

Imagine you are building a system where users can have different roles or permissions. Instead of storing a true or false for each permission, you can use bitwise OR. This allows you to combine all permissions into a single number. This number is then easy to store in a database or pass between different parts of your program.

1

Define Your Permission Flags

Assign a unique power-of-2 number to each permission. This ensures each flag occupies its own bit position.

javascript
1const PERM_VIEW = 1; // 0001
2const PERM_EDIT = 2; // 0010
3const PERM_DELETE = 4; // 0100
4const PERM_ADMIN = 8; // 1000
2

Combine Permissions for a User

Use the bitwise OR operator (|) to combine the specific permissions a user should have. This creates a single number representing their total access.

javascript
1let userRole = PERM_VIEW | PERM_EDIT; // User can view and edit (0001 | 0010 = 0011, decimal 3)
2console.log(`User role value: ${userRole}`); // Outputs: 3
3
4// An admin user would have all permissions
5let adminRole = PERM_VIEW | PERM_EDIT | PERM_DELETE | PERM_ADMIN;
6console.log(`Admin role value: ${adminRole}`); // Outputs: 15 (0001 | 0010 | 0100 | 1000 = 1111)
3

Add a New Permission to an Existing Role

If you need to grant an additional permission to a user, you can use bitwise OR again. This will 'turn on' the new bit without affecting existing ones.

javascript
1let currentPermissions = 3; // User can VIEW and EDIT (0011)
2
3// Grant DELETE permission to this user
4currentPermissions = currentPermissions | PERM_DELETE; // 0011 | 0100 = 0111 (decimal 7)
5console.log(`New permissions value: ${currentPermissions}`); // Outputs: 7
6
7// The user now has VIEW, EDIT, and DELETE permissions.

Ignoring Bitwise Operators for Flags

If you try to manage many true/false options without bitwise operators, you might end up with many separate variables or a complex object. This can make your code harder to read, less efficient to store, and more difficult to pass around. Bitwise OR provides a clear, concise way to handle these types of combined settings.

Bitwise OR Reference

Bitwise OR Reference

OperatorNamePurposeExample
`|`Bitwise ORCompares bits. If either bit is 1, result is 1.`5 | 3` results in `7`
`||`Logical ORCompares boolean values. Returns first truthy value or last value. Short-circuits.`true || false` results in `true`
`&`Bitwise ANDCompares bits. If both bits are 1, result is 1.`5 & 3` results in `1`
`^`Bitwise XORCompares bits. If bits are different, result is 1.`5 ^ 3` results in `6`

Test Your Knowledge

Test Your Knowledge

Test Your Knowledge

Quick Check

What is the result of 10 | 6?

Quick Check

Which of the following is the primary use case for bitwise OR (|)?

Quick Check

If OPTION_A = 1 (binary 001) and OPTION_B = 4 (binary 100), what is OPTION_A | OPTION_B?

Quick Check

Which operator performs a logical OR operation, often used for short-circuiting?

Quick Reference

Quick Reference

Quick Reference

Pro Tips
  • 1Bitwise OR (|) — Compares two numbers bit by bit; if either bit is 1, the result bit is 1.
  • 2Binary Representation — JavaScript converts numbers to 32-bit binary for bitwise operations.
  • 3Setting Flags — It's ideal for combining multiple true/false options (flags) into a single integer.
  • 4Unique Bits — Each flag should be a power of 2 (1, 2, 4, 8, ...) to ensure it occupies a unique bit position.
  • 5Combining Flags — Use flag1 | flag2 to create a new number that has both flags set.
  • 6Adding Flags — To add a new flag to an existing set, use currentFlags = currentFlags | newFlag.
  • 7Logical vs. Bitwise — Do not confuse | (bitwise OR) with || (logical OR); they serve different purposes.
  • 8Integer Only — Bitwise operators only work with integers; floating-point numbers are truncated.
  • 9Efficiency — Bitwise operations are very fast because they are low-level operations on how computers handle numbers.
  • 10Common Uses — Found in game development, configuration settings, and managing user permissions.

Bitwise AND (&)

Learn how the bitwise AND operator checks if specific flags are set within a combined value.

Bitwise XOR (^)

Explore the bitwise XOR operator for toggling bits and its unique applications.

Binary Numbers

Deepen your understanding of how computers represent numbers using binary (base-2).

Logical Operators

Review the || (logical OR) and && (logical AND) operators and their differences from bitwise operators.

You Mastered Bitwise OR!

Congratulations! You now understand the JavaScript bitwise OR operator (|). You can convert numbers to binary, perform OR operations, and use this powerful tool for setting and combining flags in your code. Keep practicing to make these concepts second nature!

Try it in the Javascript Compiler

Run and experiment with Javascript code right in your browser — no setup needed.

Continue Learning