Math.log2()
Math.log2(x) Math.log2() returns the base-2 logarithm of a number. In computer science, this is fundamental to understanding binary systems, algorithm complexity, and data representation.
Syntax
Math.log2(x)
Parameters
| Parameter | Type | Description |
|---|---|---|
x | number | A number greater than or equal to zero |
Return Value
| Input | Return Value |
|---|---|
x > 0 | The base-2 logarithm of x |
x = 1 | 0 |
x = 0 | -Infinity |
x < 0 | NaN |
x = NaN | NaN |
Why Base-2?
Binary logarithms are everywhere in computing:
- Bit depth: The number of bits needed to represent
nvalues is⌊log₂(n)⌋ + 1 - Binary search: Time complexity is O(log₂ n)
- Tree structures: Height of balanced binary trees is log₂ n
- Information theory: Base-2 gives bits (Shannon entropy)
Examples
Calculating bit depth
// How many bits to store 256 distinct values?
const bits = Math.floor(Math.log2(256)) + 1;
console.log(bits);
// 8
// Practical: minimum bits for RGB color (16.7 million colors)
const colorBits = Math.ceil(Math.log2(16777216));
console.log(colorBits);
// 24
Bit depth answers a practical question — “how many bits do I need to represent this range?” — but the raw logarithmic value is also useful on its own. Knowing that log₂(100) is about 6.64 tells you that 100 sits between 2⁶ (64) and 2⁷ (128), which is valuable for sizing buffers, estimating iteration counts, and reasoning about divide-and-conquer algorithms.
Binary logarithms
// log₂(1) = 0 (anything to the power of 0 is 1)
console.log(Math.log2(1));
// 0
// log₂(2) = 1, log₂(4) = 2, log₂(8) = 3
console.log(Math.log2(2)); // 1
console.log(Math.log2(4)); // 2
console.log(Math.log2(8)); // 3
// Powers of 2: 2^10 = 1024
console.log(Math.log2(1024));
// 10
// Non-powers of 2 give fractional results
console.log(Math.log2(100));
// 6.643856189774724
The examples above all use positive, finite inputs where log₂ is well-defined mathematically. But real code has to deal with boundary inputs — zero, negative numbers, and non-finite values. Each of these produces a specific sentinel return value that you can check for explicitly before proceeding with a calculation.
Handling edge cases
// Zero returns -Infinity
console.log(Math.log2(0));
// -Infinity
// Negative numbers return NaN (real log undefined)
console.log(Math.log2(-1));
// NaN
// NaN propagates
console.log(Math.log2(NaN));
// NaN
// Infinity returns Infinity
console.log(Math.log2(Infinity));
// Infinity
Math.log2() is one of three logarithm functions in JavaScript’s Math object. Each serves a different domain: Math.log() for natural-log scientific work, Math.log10() for engineering and order-of-magnitude estimates, and Math.log2() for computer science. You can convert between any two bases with the change-of-base formula.
Comparing log bases
| Function | Base | Use Case |
|---|---|---|
Math.log(x) | e (≈2.718) | Scientific calculations |
Math.log2(x) | 2 | Computer science, binary |
Math.log10(x) | 10 | Engineering, digits |
Convert between bases:
// log₂(x) = log(x) / log(2)
const log2 = Math.log(x) / Math.log(2);
Knowing how to compute and convert log₂ values is one thing — applying them to real problems is another. Two patterns show up repeatedly: testing whether a number is an exact power of two, and estimating the number of steps a divide-and-conquer algorithm needs.
Common Patterns
Check if number is power of 2
function isPowerOfTwo(n) {
return n > 0 && (n & (n - 1)) === 0;
}
// Or using log2:
function isPowerOfTwoLog(n) {
return n > 0 && Number.isInteger(Math.log2(n));
}
console.log(isPowerOfTwo(8)); // true
console.log(isPowerOfTwo(10)); // false
The power-of-two check asks a binary yes/no question: is this number an exact power? But many algorithms need the ceiling of log₂ instead — the minimum number of bits or steps required, regardless of whether the input is an exact power. Binary search is the classic example: searching 100 elements takes 7 steps because ⌈log₂(100)⌉ = 7.
Finding array index in binary search
function binarySearchSteps(arrayLength, targetIndex) {
return Math.ceil(Math.log2(arrayLength));
}
console.log(binarySearchSteps(100, 50)); // 7
console.log(binarySearchSteps(1000, 500)); // 10
Floating-point precision
Math.log2() returns a floating-point number. For exact powers of 2, the result is an integer, but floating-point representation can introduce tiny rounding errors for other inputs. Testing whether a number is a power of 2 using Number.isInteger(Math.log2(n)) is unreliable for large values — the bitwise approach n > 0 && (n & (n - 1)) === 0 is faster and exact.
Math.log2() vs Math.log() / Math.LN2
Before Math.log2() was added in ES2015, the standard workaround was Math.log(x) / Math.LN2. The two approaches produce the same results for most inputs, but Math.log2() may be more accurate for exact powers of 2 because some engines implement it with a dedicated hardware instruction. Math.log2(1024) returns exactly 10; the Math.log approach may return 9.999999999999998 due to floating-point division.
Relationship to bit operations
Many low-level binary operations map directly to Math.log2(). The number of bits required to represent n distinct values is Math.ceil(Math.log2(n)) — this gives the bit depth for color channels, address spaces, and lookup tables. The depth of a complete binary tree with n leaves is Math.ceil(Math.log2(n)). Understanding these relationships makes it straightforward to reason about algorithm complexity without memorizing constants.
Performance Note
Math.log2() is a native JavaScript function with hardware-level optimization. For bulk calculations, avoid creating new functions in tight loops.
When Math.log2() helps
Math.log2() is useful whenever a problem can be phrased in powers of two. That includes binary sizes, tree depth, index growth, and any situation where you want to reason about how many doublings it takes to reach a value. It maps directly to the way computers store and count data, which makes the result easier to interpret in technical code.
It is also a better fit than Math.log(x) / Math.LN2 when readability matters. The dedicated function says exactly what the code is doing, and that reduces the chance of mixing bases or carrying the wrong constant through a calculation.
See Also
- Math.log() — natural logarithm
- Math.log10() — base-10 logarithm
- Math.log1p() — log(1+x)
- Math.exp() — exponential function
- Math.pow() — exponentiation