Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Math

Math.log()

Reference for Math.log(): the natural logarithm, logarithms in any base, zero and negative input, and the more precise log1p() for tiny values.

Math.log() returns the natural logarithm of a number, that is, the logarithm to base e (about 2.71828). It answers the question: "to what power must e be raised to get this number?" So Math.log(Math.E) is 1 and Math.log(1) is 0.

Despite the name, it is not the base-10 logarithm that calculators often call "log". For base 2 and base 10 there are dedicated methods, and any other base can be built from the natural logarithm.

JavaScript
Math.log(x)

Try it

JS Natural logarithm

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

No output.

JS Any base, and growth time

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

No output.

Syntax

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

Return value: the natural logarithm of x. Math.log(0) is -Infinity; negative numbers and non-numeric values give NaN; Math.log(Infinity) is Infinity.

Exceptions: a BigInt argument throws a TypeError.

Usage notes

  • Change of base. log_b(x) is Math.log(x) / Math.log(b). The result can have a small rounding error: Math.log(81) / Math.log(3) is 4.000000000000001. For bases 2 and 10 prefer Math.log2() and Math.log10().
  • Domain. Only positive numbers have a real logarithm. Treat NaN and -Infinity as signals for invalid input.
  • Math.log1p(x) computes Math.log(1 + x) accurately when x is very close to zero, where adding 1 first would throw away digits. It is the better tool for small interest rates and probabilities.
  • Growth and decay. Solving "how long until a quantity doubles?" or "how many halvings?" is a logarithm problem, as in the second example.
  • Data scaling. Logarithms compress values that span many orders of magnitude, useful when charting data.
  • Exponent inverse. Math.exp() undoes Math.log(), apart from tiny rounding errors.
  • Not console.log. The two share only a word. Math.log() produces a number and prints nothing.

Browser support

Supported in every browser and in Node.js. Math.log1p() is part of ES2015.