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
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.
1let num1 = 5; // Binary: 01012let num2 = 3; // Binary: 001134// Perform bitwise OR operation5let result = num1 | num2;67console.log(result); // This will output 7 (Binary: 0111)89/*10 How it works:11 num1: 0101 (decimal 5)12 num2: 0011 (decimal 3)13 ------14 OR: 0111 (decimal 7)1516 - First bit (rightmost): 1 OR 1 = 117 - Second bit: 0 OR 1 = 118 - Third bit: 1 OR 0 = 119 - Fourth bit: 0 OR 0 = 020*/
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.
1let settingA = 8; // Binary: 10002let settingB = 4; // Binary: 01003let settingC = 1; // Binary: 000145// Combine settingA and settingB6let combinedAB = settingA | settingB; // 1000 | 0100 = 1100 (decimal 12)7console.log(`Combined A and B: ${combinedAB}`); // Outputs: 1289// Combine all three settings10let combinedABC = settingA | settingB | settingC; // 1000 | 0100 | 0001 = 1101 (decimal 13)11console.log(`Combined A, B, and C: ${combinedABC}`); // Outputs: 131213/*14 Step-by-step for combinedABC:15 settingA: 100016 settingB: 010017 settingC: 000118 ----------19 Result: 1101 (decimal 13)2021 Notice how each '1' from any of the original numbers makes a '1' in the final result.22*/
const READ_PERMISSION = 1;const WRITE_PERMISSION = 2;const EXECUTE_PERMISSION = 4;// This adds the numbers, but doesn't correctly represent combined flagslet 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
const READ_PERMISSION = 1; // Binary: 001const WRITE_PERMISSION = 2; // Binary: 010const EXECUTE_PERMISSION = 4; // Binary: 100// This correctly combines flags using their distinct bit positionslet 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.
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);
const PERM_READ = 1; // Binary: 001const PERM_WRITE = 2; // Binary: 010const PERM_DELETE = 4; // Binary: 100// Combine permissions into a single numberlet 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);
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);
const PERM_READ = 1; // Binary: 001const PERM_WRITE = 2; // Binary: 010const PERM_DELETE = 4; // Binary: 100// Combine permissions into a single numberlet 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.
Define Your Permission Flags
Assign a unique power-of-2 number to each permission. This ensures each flag occupies its own bit position.
1const PERM_VIEW = 1; // 00012const PERM_EDIT = 2; // 00103const PERM_DELETE = 4; // 01004const PERM_ADMIN = 8; // 1000
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.
1let userRole = PERM_VIEW | PERM_EDIT; // User can view and edit (0001 | 0010 = 0011, decimal 3)2console.log(`User role value: ${userRole}`); // Outputs: 334// An admin user would have all permissions5let adminRole = PERM_VIEW | PERM_EDIT | PERM_DELETE | PERM_ADMIN;6console.log(`Admin role value: ${adminRole}`); // Outputs: 15 (0001 | 0010 | 0100 | 1000 = 1111)
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.
1let currentPermissions = 3; // User can VIEW and EDIT (0011)23// Grant DELETE permission to this user4currentPermissions = currentPermissions | PERM_DELETE; // 0011 | 0100 = 0111 (decimal 7)5console.log(`New permissions value: ${currentPermissions}`); // Outputs: 767// 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
| Operator | Name | Purpose | Example |
|---|---|---|---|
| `|` | Bitwise OR | Compares bits. If either bit is 1, result is 1. | `5 | 3` results in `7` |
| `||` | Logical OR | Compares boolean values. Returns first truthy value or last value. Short-circuits. | `true || false` results in `true` |
| `&` | Bitwise AND | Compares bits. If both bits are 1, result is 1. | `5 & 3` results in `1` |
| `^` | Bitwise XOR | Compares bits. If bits are different, result is 1. | `5 ^ 3` results in `6` |
Test Your Knowledge
Test Your Knowledge
What is the result of 10 | 6?
Which of the following is the primary use case for bitwise OR (|)?
If OPTION_A = 1 (binary 001) and OPTION_B = 4 (binary 100), what is OPTION_A | OPTION_B?
Which operator performs a logical OR operation, often used for short-circuiting?
Quick Reference
Quick Reference
- 1Bitwise OR (
|) — Compares two numbers bit by bit; if either bit is1, the result bit is1. - 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 | flag2to 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.