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.
Math.log(x)
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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)isMath.log(x) / Math.log(b). The result can have a small rounding error:Math.log(81) / Math.log(3)is4.000000000000001. For bases 2 and 10 preferMath.log2()andMath.log10(). - Domain. Only positive numbers have a real logarithm. Treat
NaNand-Infinityas signals for invalid input. Math.log1p(x)computesMath.log(1 + x)accurately whenxis very close to zero, where adding1first 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()undoesMath.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.