Bitwise Operators

Learn how JavaScript bitwise operators work directly on the binary representations of numbers at the bit level.

What is a Bitwise Operator?Link to this section

A bitwise operator is a special tool used in programming to manipulate the individual bits that make up a number in computer memory. Instead of looking at a number as a whole value like 5 or 9, it looks at its binary form made of zeros and ones. These operators perform fast mathematical and logical comparisons on those binary digits.

This compares the binary bits of 5 and 1 to produce a new number.

  • `&` is the **bitwise operator** that compares two numbers.
  • `5` and `1` are the **operands** being converted to binary.
  • `console.log` prints the final decimal result of the bit manipulation.

They are used in low-level programming, graphics manipulation, and setting compact flags for permissions.

Why Do We Need Bitwise Operators?Link to this section

While regular math operators handle whole decimal numbers, bitwise operators let developers manage data at the absolute lowest memory level for maximum speed and efficiency.

  • Manage multiple boolean permissions compactly using a single integer flag.
  • Compress color channels in web graphics and image processing applications.
  • Perform ultra-fast arithmetic operations like quick integer multiplication or division by powers of two.
  • Implement low-level cryptography and data encryption algorithms.
  • Optimize data storage in memory-constrained embedded systems or games.
  • Handle network packet flags and protocol headers efficiently.
  • Mask specific bits to isolate flags or status codes in hardware sensors.

Combining user permissions into a single variable using bitwise OR.

By combining bits using bitwise OR, a single integer can store multiple distinct boolean settings at the same time.

About Bitwise OperatorsLink to this section

JavaScript internally converts numbers from standard 64-bit floating-point numbers into 32-bit signed integers before applying any bitwise operation. Once the operation finishes, it converts them back to regular JavaScript numbers. There are several categories of bitwise operators including AND, OR, XOR, NOT, and three types of shifts.

CategoryOperatorsPurpose
Logical Bitwise&, |, ^, ~Perform boolean logic on individual bit positions
Shift Bitwise<<, >>, >>>Move bits left or right by a specified number of positions

Bitwise NOT inverts all the bits of the 32-bit integer.

Types of Bitwise OperatorsLink to this section

1. Bitwise AND (`&`)Link to this section

The bitwise AND operator compares two bits and returns 1 only if both bits are 1. If either bit is 0, it returns 0 for that position.

note

Any bit combined with 0 using bitwise AND always results in 0.

warning

Non-number operands are implicitly converted to 32-bit integers, which can lead to unexpected zeros like when using strings.

2. Bitwise OR (`|`)Link to this section

The bitwise OR operator compares two bits and returns 1 if at least one of the bits is 1. It only returns 0 if both bits are 0.

tip

Use bitwise OR with 0 as a quick trick to truncate decimal numbers into integers, though it only works safely for 32-bit ranges.

3. Bitwise XOR (`^`)Link to this section

The bitwise XOR operator compares two bits and returns 1 if the bits are different from each other. If both bits are 0 or both are 1, it returns 0.

note

XORing a value with the same number twice restores the original value, making it useful for simple data scrambling.

4. Bitwise NOT (`~`)Link to this section

The bitwise NOT operator is a unary operator that flips all the bits of the number, changing every 0 to 1 and every 1 to 0. It effectively calculates the negative minus one value of the number.

warning

Because ~(-1) evaluates to 0, using bitwise NOT with indexOf requires careful handling since 0 evaluates to falsy in conditions.

5. Left Shift (`<<`)Link to this section

The left shift operator moves all the bits in the binary representation to the left by a specified number of positions, filling empty spaces on the right with zeros.

tip

Shifting a number left by n positions is mathematically equivalent to multiplying that number by 2 to the power of n.

6. Sign-Propagating Right Shift (`>>`)Link to this section

The sign-propagating right shift operator moves bits to the right by a specified number of positions while preserving the original sign bit of the number.

tip

Shifting right by n positions is equivalent to dividing by 2 to the power of n and rounding down towards negative infinity.

7. Zero-Fill Right Shift (`>>>`)Link to this section

The zero-fill right shift operator moves bits to the right and always fills the leftmost empty positions with zeros, regardless of whether the original number was positive or negative.

warning

Applying zero-fill right shift to negative numbers converts them into extremely large positive 32-bit unsigned integers.

Bitwise Operator PrecedenceLink to this section

Bitwise operators have lower precedence than arithmetic operators like addition and multiplication, but higher precedence than comparison operators. This means adding numbers without parentheses can cause bugs.

tip

Always use parentheses around bitwise expressions when combining them with arithmetic or comparison operators to ensure correct evaluation order.

Complete Coding ExampleLink to this section

A complete script managing user access flags and shifting permission values.

This script demonstrates combining permissions with OR, checking permissions with AND, and scaling values using a left shift.

Important NotesLink to this section

  • Bitwise operators convert operands into 32-bit signed integers before running.
  • The bitwise AND operator returns 1 only when both bits are 1.
  • The bitwise OR operator returns 1 when at least one bit is 1.
  • The bitwise XOR operator returns 1 when bits are different.
  • The bitwise NOT operator inverts all bits and changes the number sign.
  • Left shift multiplies a number by powers of two.
  • Sign-propagating right shift divides a number by powers of two.
  • Zero-fill right shift always inserts zeros on the left side.
  • Operator precedence means bitwise operations often require explicit parentheses.
  • Non-number inputs are converted to numeric values or zero during execution.

SummaryLink to this section

Bitwise operators provide powerful low-level control over numerical data by manipulating individual binary bits. Understanding how to use AND, OR, XOR, NOT, and shift operators allows developers to optimize data storage, handle permissions efficiently, and perform rapid calculations. Mastering these operators completes your foundation in JavaScript operator tools.

Check Your UnderstandingLink to this section

Javascript Bitwise Operators quiz
Question 1 of 6

What is the result of `5 & 1` in JavaScript?

Practice ChallengesLink to this section

1. Even or Odd Check

easy

Write a program using a bitwise operator to check if the number 7 is odd. Print true if odd and false if even.

Expected output

true

Hint: Compare the number with 1 using bitwise AND.

2. Double the Price

easy

A shop item costs 12 dollars. Use a bitwise shift operator to multiply this price by 2 and print the result.

Expected output

24

Hint: Use the left shift operator by 1 position.

3. Permission Flag Checker

medium

A user has permissions set to 5 (binary 0101). Check if the permission flag 1 (binary 0001) is active using bitwise AND and print the boolean result.

Expected output

true

Hint: Use the & operator and compare the outcome against 0.

4. Simple Number Scrambler

medium

Take an employee ID number 45, encrypt it using bitwise XOR with a key of 12, then decrypt it back using XOR and print the final decrypted ID.

Expected output

45

Hint: XOR the encrypted result with the key again to restore the original value.

5. Fast Integer Division

hard

An exam total score is 36. Use a right shift operator to divide the score by 4 and print the final result.

Expected output

9

Hint: Dividing by 4 is equivalent to right shifting by 2 positions (2^2 = 4).

Rate this content

Sign in to rate

Discussion

Sign in to join the discussion