Math.log2()

Math.log2(x)
Returns: number · Added in vES1 · Updated March 13, 2026 · Math
math logarithm binary bits numbers

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

ParameterTypeDescription
xnumberA number greater than or equal to zero

Return Value

InputReturn Value
x > 0The base-2 logarithm of x
x = 10
x = 0-Infinity
x < 0NaN
x = NaNNaN

Why Base-2?

Binary logarithms are everywhere in computing:

  • Bit depth: The number of bits needed to represent n values 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

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

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

Comparing Log Bases

FunctionBaseUse Case
Math.log(x)e (≈2.718)Scientific calculations
Math.log2(x)2Computer science, binary
Math.log10(x)10Engineering, digits

Convert between bases:

// log₂(x) = log(x) / log(2)
const log2 = Math.log(x) / Math.log(2);

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
function binarySearchSteps(arrayLength, targetIndex) {
  return Math.ceil(Math.log2(arrayLength));
}

console.log(binarySearchSteps(100, 50));   // 7
console.log(binarySearchSteps(1000, 500)); // 10

Performance Note

Math.log2() is a native JavaScript function with hardware-level optimization. For bulk calculations, avoid creating new functions in tight loops.

See Also