exponential

Math.log2

Returns the base-2 logarithm of a number. Introduced in ES2015 and useful for information theory, tree depths, and bit counts.

Math.log2(x)

Parameters & edge cases

Case Behavior
x A positive number
power of 2 check Number.isInteger(Math.log2(n)) tests if n is a power of 2
ES2015+ Polyfill: Math.log(x) / Math.LN2

Examples

console.log(Math.log2(8));     // 3

2³ = 8.

console.log(Math.log2(1));     // 0

log_2(1) = 0.

console.log(Math.log2(1024));  // 10

2¹⁰ = 1024 — classic KB conversion.

console.log(Math.log2(3));     // 1.584962500721156

Non-power-of-2 inputs give irrational results.

Gotcha

Due to floating-point, Math.log2(8) is exactly 3 in most engines, but Math.log2(1e21) can be off by ~1 ULP — never compare with strict equality for large inputs.

Related

← All JS Math methods · Array methods