Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Math

Math.log2() and Math.log10()

Reference for Math.log2() and Math.log10(): base-2 and base-10 logarithms, counting digits and bits, and why they beat dividing natural logs.

Math.log2(x) returns the base-2 logarithm of x, and Math.log10(x) returns the base-10 logarithm. They answer "2 to what power gives x?" and "10 to what power gives x?". For example Math.log2(8) is 3 and Math.log10(1000) is 3.

You could compute these with Math.log(x) / Math.log(2), but the dedicated functions are more accurate for exact powers and easier to read.

JavaScript
Math.log2(x)
Math.log10(x)

Try it

JS Powers of 2 and 10

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Counting digits and bits

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
Math.log2(x)
Math.log10(x)
Name Description
x A positive number (or a value that converts to one).

Return value: the logarithm of x in base 2 or base 10. For 0 the result is -Infinity; for negative numbers and non-numeric values it is NaN; for Infinity it is Infinity.

Exceptions: a BigInt argument throws a TypeError.

Usage notes

  • Exact for powers. Engines return whole numbers for exact powers of the base, which a division of natural logarithms often does not: Math.log(1000) / Math.LN10 is 2.9999999999999996.
  • Digit count. Math.floor(Math.log10(n)) + 1 counts the digits of a positive integer. For very large integers, or if exactness matters, use String(n).length.
  • Bit length. Math.floor(Math.log2(n)) + 1 gives the bits needed. Math.clz32() computes this for 32-bit integers without floating point.
  • Algorithm analysis. Binary search, balanced trees and sorting costs involve log2(n).
  • Zero and negatives are invalid input; check before calling.
  • Other bases: use Math.log(x) / Math.log(base) and round if a whole number is expected.
  • Decibels and pH use base-10 logarithms: 10 * Math.log10(ratio).

Browser support

Both methods are part of ES2015 and supported in all current browsers.