Home/Blog/Programming/Bitwise AND (&) in JavaScript: A 5-minute guide
Bitwise AND (&) in JavaScript
Home/Blog/Programming/Bitwise AND (&) in JavaScript: A 5-minute guide

Bitwise AND (&) in JavaScript: A 5-minute guide

7 min read
May 02, 2025
content
What are bitwise operators?
Why use bitwise operations?
Common bitwise operators in JavaScript
How bitwise operations work under the hood
Understanding the bitwise AND (&) operator
Example: Performing AND (&) on two numbers
Real-world applications of the AND (&) operator
Checking if a number is even or odd (without %)
Turning off specific bits (Bit masking)
Checking if a specific bit is set
Advanced bitwise techniques to explore
Finding a missing number in an array using XOR (^)
Finding the first set bit using the left shift (<<)
Checking if a number is a power of 2 using AND (&)
Bitwise tricks and optimization strategies
Swapping two numbers without a temporary variable
Counting the number of 1s in a binary representation (Hamming weight)
Wrap up and next steps

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

Key takeaways:

  • Bit manipulation applies logical operations on binary values, offering efficient computation with O(1)O(1) complexity.

  • Common bitwise operators include AND (&), OR (|), NOT (~), XOR (^), and bit-shifting (<<, >>).

  • Bit manipulation is widely used in device control, encryption, data compression, and error correction.

  • The bitwise AND operator performs a logical AND on binary numbers, commonly used for tasks like checking even/odd and bit masking.

  • JavaScript performs bitwise operations on 32-bit integers, converting them back to 64-bit after execution.

In programming, both speed and efficiency matter. While most developers rely on arithmetic operations for number manipulation, bitwise operations provide an even faster alternative. They allow direct manipulation of binary data at the bit level, making them faster, memory-efficient, and widely used in low-level programming, cryptography, and optimization problems.

Grokking Dynamic Programming Interview in JavaScript

Cover
Grokking Dynamic Programming Interview in JavaScript

Some of the toughest questions in technical interviews require dynamic programming solutions. Dynamic programming (DP) is an advanced optimization technique applied to recursive solutions. However, DP is not a one-size-fits-all technique, and it requires practice to develop the ability to identify the underlying DP patterns. With a strategic approach, coding interview prep for DP problems shouldn’t take more than a few weeks. This course starts with an introduction to DP and thoroughly discusses five DP patterns. You’ll learn to apply each pattern to several related problems, with a visual representation of the working of the pattern, and learn to appreciate the advantages of DP solutions over naive solutions. After completing this course, you will have the skills you need to unlock even the most challenging questions, grok the coding interview, and level up your career with confidence. This course is also available in C++, Java, and Python—with more coming soon!

25hrs
Intermediate
44 Challenges
868 Illustrations

One of the most fundamental bitwise operators is the bitwise AND (&) operator. This operator is commonly used to check even/odd numbers, set or clear specific bits, perform bit masking, and handle low-level optimizations.

Understanding bitwise operations is a must-have skill if you’re preparing for coding interviews or looking to optimize your JavaScript code. By the end of this blog, you’ll have a clear grasp of how the AND (&) operator works, its practical applications, and how to use it efficiently in JavaScript.

What are bitwise operators?#

Before diving into the bitwise AND (&) operator, let’s quickly understand bitwise operations and how they work in JavaScript.

A bitwise operation manipulates individual bits of a binary number rather than performing operations on whole numbers. Since computers store everything in binary (0s and 1s), bitwise operations allow you to interact directly with binary representations instead of using high-level arithmetic functions.

If you’re eager to dive deeper into bit-level operations and sharpen your problem-solving skills for coding interviews, check out the following Educative’s comprehensive course. It covers everything from fundamental bitwise operations to advanced problem-solving techniques, equipping you with the knowledge needed to tackle even the trickiest bit manipulation challenges in FAANG and competitive programming interviews.

Master how bit-level operations are computed

Cover
Grokking Bit Manipulation for Coding Interviews

This course teaches bit manipulation, a powerful technique to enhance algorithmic and problem-solving skills. It is a critical topic for those preparing for coding interviews for top tech companies, startups and industry leaders. Competitive programmers can take full advantage of this course by running most of the bit-related problems in O(1) complexity. The course will begin by educating you about the number system and its representation, decimal and binary, followed by the six bitwise operators: AND, OR, NOT, XOR, and bit-shifting (left, right). You will receive ample practical experience working through practice problems to improve your comprehension. Upon completing this course, you will be able to solve problems with greater efficiency and speed.

3hrs
Intermediate
7 Challenges
11 Quizzes

Why use bitwise operations?#

  • Super fast: Directly supported by the processor, making them faster than arithmetic operations.

  • Constant time complexity O(1)O(1): No matter how large the numbers are, bitwise operations take the same amount of time.

  • Low-level programming: Used in encryption, compression, graphics, networking, and security protocols.

  • Memory efficient: Helps optimize data storage and perform compact calculations.

Common bitwise operators in JavaScript#

Operator

Symbol

Function

Bitwise AND

&

Sets each bit to 1 if both corresponding bits are 1.

Bitwise OR

| 

Bitwise OR ( | ) returns 1 if any of the operands is set (i.e., 1) and 0 in any other case.

Bitwise XOR

^

Sets each bit to 1 if only one of the corresponding bits is 1.

Bitwise NOT

~

Inverts all bits (1s become 0s, and vice versa).

Left Shift

<<

Shifts bits to the left (multiplies by 2).

Right Shift

>>

Shifts bits to the right (divides by 2).

How bitwise operations work under the hood#

JavaScript stores numbers as 64-bit floating-point values (IEEE 754 standard), but bitwise operations are performed on 32-bit signed integers. What does this mean? It means:

  • Before executing a bitwise operation, JavaScript converts numbers to 32-bit signed integers.

  • After performing the operation, the result is converted back to a 64-bit floating-point number.

Understanding the bitwise AND (&) operator#

The bitwise AND (&) operator performs a logical AND operation on each corresponding bit of two numbers. Note:

  • If both corresponding bits are 1, the result is 1.

  • Otherwise, the result is 0.

It can be visualized as a series circuit like this:

How a series circuit works
How a series circuit works

When both switches are on, the light is on. If any of the switches is off, the bulb does not light, resulting in the output being 0.

Example: Performing AND (&) on two numbers#

Let’s break it down using 12 & 25 in JavaScript.

Javascript (babel-node)
let a = 12; // Binary: 00001100
let b = 25; // Binary: 00011001
let result = a & b; // Binary: 00001000 (decimal: 8)
console.log(result); // Output: 8

Let’s understand how the result is calculated below:

Bit Position

12 (00001100)

25 (00011001)

Result (00001000)

Bit 1

0

0

0

Bit 2

0

0

0

Bit 3

0

0

0

Bit 4

0

1

0

Bit 5

1

1

1

Bit 6

1

0

0

Bit 7

0

0

0

Bit 8

0

0

0

Since only one bit (position 5) is 1 in both numbers, the result is 8 (00001000).

Try this: What do you think 7 & 3 will output? Run it in your JavaScript console!

Real-world applications of the AND (&) operator#

Let’s have a look at the real-world applications:

Checking if a number is even or odd (without %)#

Did you know you can check even or odd numbers without using modulo (%)?

Javascript (babel-node)
function isEven(num) {
return (num & 1) === 0;
}
console.log(isEven(10)); // true (even)
console.log(isEven(7)); // false (odd)

Why does this work?

  • Even numbers end in 0 in binary.

  • Odd numbers end in 1 in binary.

  • The last bit of a binary number determines if it’s odd (1) or even (0). Using num & 1 lets you check this efficiently.

Turning off specific bits (Bit masking)#

What if you want to turn off specific bits while keeping others unchanged?

Javascript (babel-node)
let num = 255; // Binary: 11111111
let mask = 0b00001111; // Binary mask: 00001111
let result = num & mask;
console.log(result); // Output: 15 (Binary: 00001111)

This technique is widely used in cryptography, data compression, and security applications.

Checking if a specific bit is set#

Need to check if a specific bit in a number is 1?

Javascript (babel-node)
function isBitSet(num, position) {
return (num & (1 << position)) !== 0;
}
console.log(isBitSet(5, 0)); // true (Binary 00000101 → LSB is 1)
console.log(isBitSet(5, 1)); // false (Binary 00000101 → Second bit is 0)

How does this work?

  • 1 << position creates a number where only that bit is 1.

  • Using & checks if that bit is set (1) or not (0).

Used in permission handling, flag checking, and low-level programming.

Advanced bitwise techniques to explore#

Now that you’ve gained a solid understanding of the bitwise AND (&) operator, it’s time to build upon this knowledge and explore other essential bitwise techniques that can optimize your code, enhance your problem-solving skills, and prepare you for coding interviews.

Let’s look at the advanced bitwise techniques.

Finding a missing number in an array using XOR (^)#

A classic problem in coding interviews is finding the missing number in an array of size n containing numbers from 0 to n, but with one number missing.

Instead of using sorting O(nlogn)O(n logn) or summation O(n)O(n), you can solve this problem in O(1)O(1) space and O(n)O(n) time complexity using the XOR (^) operator.

Why does XOR work here?

  • XOR of a number with itself is always 0 (a ^ a = 0).

  • XOR of a number with 0 remains unchanged (a ^ 0 = a).

  • Since numbers appear twice (except the missing one), their XOR cancels out, leaving only the missing number.

Javascript (babel-node)
function findMissingNumber(arr, n) {
let xorAll = 0;
let xorArr = 0;
// XOR all numbers from 0 to n
for (let i = 0; i <= n; i++) {
xorAll ^= i;
}
// XOR all numbers in the given array
for (let num of arr) {
xorArr ^= num;
}
// The missing number is found using XOR property
return xorAll ^ xorArr;
}
console.log(findMissingNumber([0, 1, 3, 4, 5], 5)); // Output: 2

Try it out: What if there were multiple missing numbers? How would you modify this approach?

Finding the first set bit using the left shift (<<)#

The first set bit is the position of the least significant 1 bit in a number’s binary representation. This is useful in low-level bit manipulations like bitwise compression, flagging mechanisms, and optimizing memory usage.

Javascript (babel-node)
function getFirstSetBitPosition(num) {
let position = 1;
while ((num & 1) === 0) {
num >>= 1;
position++;
}
return position;
}
console.log(getFirstSetBitPosition(18)); // Output: 2 (Binary: 10010 → First `1` at position 2)

Why does this work?

  • We right shift (>>) until we find a 1.

  • The position count keeps increasing until we locate the first set bit.

Where is this used? In bitwise compression, error detection, and CPU instruction optimization.

Checking if a number is a power of 2 using AND (&)#

A number is a power of 2 if it has exactly one 1 in its binary representation (e.g., 2 (10), 4 (100), 8 (1000)).

A simple check using AND (&) can determine this:

Javascript (babel-node)
function isPowerOfTwo(num) {
return num > 0 && (num & (num - 1)) === 0;
}
console.log(isPowerOfTwo(8)); // true (1000)
console.log(isPowerOfTwo(6)); // false (0110)

Why does this work?

  • A power of 2 has only one set bit (1000, 10000 etc.).

  • Subtracting 1 flips all bits after the rightmost 1 (1000 - 1 = 0111).

  • num & (num - 1) should be 0 only for powers of 2.

This trick is commonly used in game development, networking (buffer sizes), and cryptography!

Bitwise tricks and optimization strategies#

Now that you’ve explored bitwise AND (&) and related techniques, let’s discuss where bitwise operations excel in real-world applications:

Swapping two numbers without a temporary variable#

Instead of using extra space, XOR swapping allows you to swap two numbers without using a third variable.

Javascript (babel-node)
function swap(a, b) {
console.log(`Before swap: a = ${a}, b = ${b}`);
a = a ^ b;
b = a ^ b;
a = a ^ b;
console.log(`After swap: a = ${a}, b = ${b}`);
}
swap(5, 10);

Why does this work?

  • a ^ b stores the XOR result in a, which helps extract the original a from b and vice versa.

  • No extra memory is required!

Counting the number of 1s in a binary representation (Hamming weight)#

Used in compression algorithms, cryptography, and AI, this technique quickly finds how many bits are set in a number.

Javascript (babel-node)
function countSetBits(num) {
let count = 0;
while (num > 0) {
num &= (num - 1); // Removes the rightmost 1
count++;
}
return count;
}
console.log(countSetBits(9)); // Output: 2 (Binary: 1001)
console.log(countSetBits(15)); // Output: 4 (Binary: 1111)

Why does this work?

  • num & (num - 1) removes the rightmost 1 in each iteration, reducing unnecessary loops.

  • This runs in O(k)O(k) complexity, where kk is the number of set bits (faster than O(n)O(n)).

Wrap up and next steps#

Mastering bitwise operations isn’t just about coding tricks—it’s about writing faster, more efficient programs. Whether you’re optimizing algorithms, working on performance-critical systems, or prepping for coding interviews, understanding how to manipulate bits is a powerful tool in your JavaScript toolkit. Next, you should check out the other bitwise operators in detail with hands-on practice, like:

  • Missing number with XOR
  • Get the first set bit with LEFT
  • Power of 2 with AND

For more hands-on learning, check out these Educative’s blogs:

These resources will further strengthen your understanding of bitwise operations and computer number systems.

To expand your JavaScript expertise, explore these related blogs:

If you want to deepen your knowledge, start your journey today with Educative’s JavaScript courses and transform your potential into expertise. Let’s build something incredible together.

Some of the latest courses available on our platform include:

Happy learning!

Frequently Asked Questions

What is >>> in JavaScript?

In JavaScript, >>> is the zero-fill right shift operator. It shifts the first operand’s binary representation to the right by the number of places specified in the second operand, and it fills the left with zeros. It’s often used for unsigned bit manipulation.

What is bitwise in JavaScript?

In JavaScript, bitwise operators perform operations on the binary (bit-level) representation of numbers. Since JavaScript stores numbers as 64-bit floating-point values, bitwise operations first convert them into 32-bit integers, perform the operation, and then convert them back.

Common bitwise operators include:

  • AND (&): Returns 1 if both bits are 1 (5 & 1 → 101 & 001 → 001 → 1).

  • OR (|): Returns 1 if either bit is 1 (5 | 1 → 101 | 001 → 101 → 5).

  • XOR (^): Returns 1 if bits are different (5 ^ 1 → 101 ^ 001 → 100 → 4).

  • NOT (~): Inverts all bits (~5 → ~(000...0101) → 111...1010 → -6).

  • Left shift (<<): Shifts bits left, multiplying the number (5 << 1 → 1010 → 10).

  • Right shift (>>): Shifts bits right, dividing by 2 (5 >> 1 → 10 → 2).

  • Zero-fill right shift (>>>): Similar to >>, but fills with 0s instead of sign bits.

Bitwise operations are commonly used for performance optimization, low-level algorithms, cryptography, and working with binary data.

What is the &= operator in JavaScript?

The &= operator in JavaScript is a bitwise AND assignment operator that combines a bitwise AND operation with assignment. Here’s how it works:

  • The &= operator performs a bitwise AND (&) operation and assigns the result to the left operand.
  • It is a shorthand for x &= y, which is equivalent to x = x & y.
  • The bitwise AND operation returns 1 only if both corresponding bits are 1, otherwise, it returns 0.
  • For example: 5 &= 3101 & 011001 → Result: 1.
  • It is commonly used for bitwise manipulations, flag-based operations, and performance optimizations in integer computations.

What is a bitwise operation in the genetic algorithm?

Bitwise operations in genetic algorithms (GAs) are used for mutation, crossover, and fitness evaluation when solutions are represented as binary strings (chromosomes). Here’s how they work:

  • Bitwise mutation: Randomly flips a bit (01 or 10) to introduce genetic diversity in the population.
  • Bitwise crossover: Exchanges specific bits between parent chromosomes using crossover masks, facilitating genetic recombination.
  • Bitwise logical operations: AND, OR, and XOR are sometimes used in fitness evaluation, especially in boolean optimization problems.

These operations enhance computational efficiency, leading to faster mutation, crossover, and selection processes in GAs.

What do you understand by bitwise AND operator?

The bitwise AND (&) operator in JavaScript performs a binary comparison between two numbers at the bit level. It returns 1 for each bit position where both corresponding bits are 1; otherwise, it returns 0. This operator is commonly used for bit manipulation, masking, and low-level optimizations.

Example:

let a = 5;  // Binary: 101
let b = 3;  // Binary: 011
console.log(a & b); // Output: 1 (Binary: 001)

Here, only the last bit is 1 in both numbers, so the result is 1. The bitwise AND operator is widely used in flag operations, permission settings, and performance-efficient computations.


Written By:
Amanda Fawcett

Free Resources