Check Power of 2 in JavaScript

What you’ll learn

  • What powers of 2 are and where they appear in real coding tasks.
  • How to use the n & (n - 1) bit trick safely with n > 0.
  • How to list all powers of 2 in a range with clean JavaScript.
  • Common edge cases with 0, negatives, and input parsing.

Overview

A positive integer is a power of 2 if it has exactly one 1 in binary.

Prerequisites

Basic JavaScript conditionals, loops, and bitwise operators.

What is a power of 2?

Values: 1, 2, 4, 8, 16, 32.... If a number cannot be reached by repeated doubling from 1, it is not a power of 2.

Live preview

Enter a value and test instantly.

Live result
Press "Run check" to view result.

Algorithm

1

Reject invalid values

If n <= 0, return false.

2

Bit test

Return (n & (n - 1)) === 0.

📜 Pseudocode

Pseudocode
if n <= 0: return false
return (n & (n - 1)) == 0
1

Check one number

JavaScript
function isPowerOfTwo(num) {
  return num > 0 && (num & (num - 1)) === 0;
}

const number = 16;
if (isPowerOfTwo(number)) {
  console.log(number + " is a power of 2.");
} else {
  console.log(number + " is not a power of 2.");
}
Try it Yourself
2

Power of 2 in range 1 to 20

JavaScript
function isPowerOfTwo(num) {
  return num > 0 && (num & (num - 1)) === 0;
}

const values = [];
for (let i = 1; i <= 20; i++) {
  if (isPowerOfTwo(i)) {
    values.push(String(i));
  }
}

console.log("Power of 2 in the range 1 to 20:");
console.log(values.join(" "));
Try it Yourself

❓ FAQ

A whole number of the form 2^k for k >= 0. Examples: 1, 2, 4, 8, 16.
For positive n, it is true only when binary n has exactly one set bit.
Yes, because 2^0 = 1.
No for this tutorial. We require n > 0.

🔄 Input / output examples

InputOutput
1616 is a power of 2.
1212 is not a power of 2.
11 is a power of 2.
00 is not a power of 2.

Edge cases

n = 0

Zero

Not treated as power of 2 in this tutorial.

Negative n

Invalid for this check

Return false for all negative values.

⏱️ Time and space complexity

MethodTimeSpace
n & (n - 1)O(1)O(1)
Divide-by-2 loopO(log n)O(1)

Summary

  • Powers of 2 are positive values with one set bit in binary.
  • Use n > 0 && (n & (n - 1)) === 0 for quick checks.
  • Handle 0 and negatives explicitly.
Did you know?

Many memory sizes and alignment rules in computing use powers of two, so this check appears often in interview rounds.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful