JavaScript Math.log(): Natural Logarithm and Custom Base Examples

JavaScript Math.log(): natural log, log base 10, custom bases via change-of-base, and Infinity / NaN edge cases.

Published

Updated

Read time 2 min read

Reviewed byDeepak Prasad

JavaScript Math.log(): Natural Logarithm and Custom Base Examples

JavaScript Math.log() returns the natural logarithm of a number. That means it calculates log base e, not log base 10. Use Math.log() for natural logs, Math.log10() for base 10, or a change-of-base formula for other bases.

Environment: Node.js v20.18.2. Each snippet is plain JavaScript; the line after it states the expected console output.


Math.log Syntax

Sketch of natural log log10 and log2 growing slowly for positive x

javascript
Math.log(x)
Output

x should be a positive number. The return value is the natural logarithm of x.


Method 1: Calculate Natural Logarithm

javascript
console.log(Math.log(Math.E));
console.log(Math.log(1));
Output

You should see 2 lines, in order: 1, 0.


Method 2: Calculate Base-10 Logarithm

javascript
console.log(Math.log(100) / Math.log(10));
Output

You should see one line logging 2.

For base 10 specifically, Math.log10(100) is clearer.


Method 3: Calculate Logarithm with Any Base

javascript
function logBase(value, base) {
  return Math.log(value) / Math.log(base);
}

console.log(logBase(8, 2));
Output

You should see one line logging 3.


Method 4: Handle 0 and Negative Inputs

javascript
console.log(Math.log(0));
console.log(Math.log(-1));
Output

You should see 2 lines, in order: -Infinity, NaN.


Common Questions About JavaScript Math.log

Is Math.log natural logarithm?

Yes. Math.log() returns the natural logarithm, which is log base e.

How do I calculate log base 10 in JavaScript?

Use Math.log10(x) or calculate Math.log(x) / Math.log(10).

Why does Math.log return NaN?

It returns NaN for negative inputs. Use positive numbers for real logarithm results.


Summary

Math.log is natural log (base e); use Math.log10 / Math.log2 when readers expect those bases, and remember log(0) is -Infinity.

JavaScript Math.log() calculates the natural logarithm of a number. Use it for log base e, or divide by Math.log(base) to calculate a custom-base logarithm. Remember that Math.log(0) returns -Infinity, and negative values return NaN.


Official Documentation

Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs …