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
Math.log
Returns the natural logarithm (base e, or ln) of a number. Inverse of Math.exp.
Math.log10
Returns the base-10 logarithm of a number. Introduced in ES2015 for accurate common-log calculations (decibels, pH, orders of magnitude).
Math.exp
Returns e^x, where e is Euler's number (~2.71828). The inverse of Math.log (the natural logarithm).
Math.expm1
Returns e^x - 1, computed accurately even for very small x. Introduced in ES2015 to avoid catastrophic cancellation near zero.
Math.log1p
Returns the natural log of (1 + x), computed accurately even for very small x. Introduced in ES2015 as the companion to expm1.