Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Power of Two Check Implementation in JavaScript

11 min readbeginner
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Power of Two Check runs in O(1) time and O(1) space, in JavaScript as in every other language.
  • ✓There is no power-of-two helper on Number or Math. The relevant primitives are the bitwise operators, specified to convert their operands with ToInt32, and Math.clz32(x), which counts leading zeros of the 32-bit representation, so 31 - Math.clz32(n) is an exact integer log2 for values below 2**32.
  • ✓A reviewer insists on the parentheses in (n & (n - 1)) === 0, because === binds tighter than & in JavaScript and dropping them ANDs n with a boolean.
  • ✓The JavaScript trap: Bitwise operators are specified to run on signed 32-bit integers, so any operand above 2**31 - 1 is truncated first and the answer becomes a fact about the low 32 bits only.
  • ✓Engines keep small integers as tagged SMIs, so n & (n - 1) on a value inside that range stays in registers and costs nothing measurable; a value held as a float64, which includes anything above the SMI range or produced by arithmetic that spilled, forces a float-to-int32 truncation on every bitwise op.

What Power of Two Check actually is

A power-of-two test asks whether a positive integer has exactly one bit set: 1, 2, 4, 8, 16, and so on. The standard trick is n > 0 combined with n & (n - 1) == 0, because subtracting one flips the lowest set bit and every bit below it, so the AND clears to zero only when there was a single set bit to begin with. Engineers reach for it when sizing hash tables, ring buffers and allocator blocks, where a power-of-two capacity turns an expensive modulo into a cheap mask (i & (cap - 1)), and when validating an alignment argument before handing it to a lower layer.

Power of Two Check in JavaScript: what you actually reach for

There is no power-of-two helper on Number or Math. The relevant primitives are the bitwise operators, specified to convert their operands with ToInt32, and Math.clz32(x), which counts leading zeros of the 32-bit representation, so 31 - Math.clz32(n) is an exact integer log2 for values below 2**32. Number.isInteger and Number.isSafeInteger do the input validation. Above 32 bits the correct tool is BigInt: n > 0n && (n & (n - 1n)) === 0n, with no width limit and no truncation.

JavaScript implementation

A reviewer insists on the parentheses in (n & (n - 1)) === 0, because === binds tighter than & in JavaScript and dropping them ANDs n with a boolean. They insist on Number.isInteger(n) before any bitwise op, since 3.7 & 2.7 truncates to 3 & 2 and answers a question about integers you never passed. Triple equals, never ==, so 0 does not compare equal to '' or false. Math.log2(n) % 1 === 0 gets rejected on sight.
javascript
// Bitwise operators truncate to signed 32-bit, so range-check before using them.
function isPowerOfTwo(n) {
  if (!Number.isSafeInteger(n) || n <= 0) return false;
  if (n > 0xFFFFFFFF) return isPowerOfTwoBig(BigInt(n));
  return (n & (n - 1)) === 0; // parens required: '===' binds tighter than '&'
}

function isPowerOfTwoBig(n) {
  return n > 0n && (n & (n - 1n)) === 0n;
}

// Exact integer log2 for values below 2**32, no floats involved.
const log2 = (n) => 31 - Math.clz32(n);

console.log(isPowerOfTwo(1024));           // true
console.log(isPowerOfTwo(4294967297));     // false, via the BigInt branch
console.log((4294967297 & 4294967296) === 0); // true -- the truncation bug
console.log(isPowerOfTwoBig(1n << 200n));  // true
console.log(log2(1024));                   // 10
console.log(2147483648 | 0);               // -2147483648

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The JavaScript-specific trap

Bitwise operators are specified to run on signed 32-bit integers, so any operand above 2**31 - 1 is truncated first and the answer becomes a fact about the low 32 bits only. isPowerOfTwo(4294967297), that is 2**32 + 1, truncates the operands to 1 and 0, ANDs to 0, and returns true. Nothing catches it: the n > 0 guard ran on the untruncated float64. Values at 2**31 also flip sign, since 2147483648 | 0 is -2147483648. Range-check below 2**32 or route the whole test through BigInt.

Performance in JavaScript, beyond the O(1)

Engines keep small integers as tagged SMIs, so n & (n - 1) on a value inside that range stays in registers and costs nothing measurable; a value held as a float64, which includes anything above the SMI range or produced by arithmetic that spilled, forces a float-to-int32 truncation on every bitwise op. The BigInt path is a different machine: each operand is a heap-allocated arbitrary-precision object and every & and - allocates a fresh one, typically an order of magnitude slower than the Number path even for single-limb values. The asymptotic cost is the same in every language, O(1) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Power of Two Check between languages.

Real-World Applications

Power of Two Check applies wherever its problem shape appears in your own code. In JavaScript, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Power of Two Check helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Power of Two Check appears frequently in phone screens and early-round coding interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Power of Two Check over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Power of Two Check to build pattern recognition. In JavaScript, demonstrate proficiency with closures and async/await to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic JavaScript code that is both correct and maintainable.

Frequently Asked Questions

Which JavaScript type or library should I use for Power of Two Check?

There is no power-of-two helper on Number or Math. The relevant primitives are the bitwise operators, specified to convert their operands with ToInt32, and Math.clz32(x), which counts leading zeros of the 32-bit representation, so 31 - Math.clz32(n) is an exact integer log2 for values below 2**32. Number.isInteger and Number.isSafeInteger do the input validation. Above 32 bits the correct tool is BigInt: n > 0n && (n & (n - 1n)) === 0n, with no width limit and no truncation.

What is the most common JavaScript mistake when implementing Power of Two Check?

Bitwise operators are specified to run on signed 32-bit integers, so any operand above 2**31 - 1 is truncated first and the answer becomes a fact about the low 32 bits only. isPowerOfTwo(4294967297), that is 2**32 + 1, truncates the operands to 1 and 0, ANDs to 0, and returns true. Nothing catches it: the n > 0 guard ran on the untruncated float64. Values at 2**31 also flip sign, since 2147483648 | 0 is -2147483648. Range-check below 2**32 or route the whole test through BigInt.

How does Power of Two Check actually perform in JavaScript?

Engines keep small integers as tagged SMIs, so n & (n - 1) on a value inside that range stays in registers and costs nothing measurable; a value held as a float64, which includes anything above the SMI range or produced by arithmetic that spilled, forces a float-to-int32 truncation on every bitwise op. The BigInt path is a different machine: each operand is a heap-allocated arbitrary-precision object and every & and - allocates a fresh one, typically an order of magnitude slower than the Number path even for single-limb values. Time complexity is O(1) and space is O(1).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

Before paying for Replit, check its student and free-tier options on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.