Math.log()

ES1+

Returns the natural logarithm (base e) of a number.

Syntax

Math.log(x)

Parameters

x number

A number

Return Value

number

The natural logarithm of the given number

Examples

JavaScript
console.log(Math.log(1));
console.log(Math.log(Math.E));
console.log(Math.log(10));
Output:
// 0 1 2.302585092994046

📌 When to Use

Use Math.log() for exponential decay calculations, logarithmic scaling, growth rate analysis, or mathematical formulas requiring natural logarithms.

⚠️ Common Mistakes

Confusing Math.log() (natural log, base e) with Math.log10() (base 10) - this is the opposite of common math notation.

Passing 0 or negative numbers which return -Infinity or NaN respectively.

✅ Best Practices

For log base n, use the change of base formula: Math.log(x) / Math.log(n).

Validate input is positive before using: if (x > 0) return Math.log(x).

⚡ Performance Notes

Logarithmic functions are more CPU-intensive than basic arithmetic. For repeated calculations with the same base, cache Math.log(base) to avoid redundant computation.

🌍 Real World Example

Decibel Sound Level Calculator

Calculate decibel levels from sound intensity using the logarithmic decibel formula.

function calculateDecibels(intensity, referenceIntensity = 1e-12) {
  if (intensity <= 0) {
    return { error: 'Intensity must be positive' };
  }

  // dB = 10 * log10(I / I0) = 10 * ln(I/I0) / ln(10)
  const decibels = 10 * Math.log(intensity / referenceIntensity) / Math.log(10);

  // Or use Math.log10 directly
  const decibelsAlt = 10 * Math.log10(intensity / referenceIntensity);

  return {
    decibels: decibels.toFixed(1),
    description: getDecibelDescription(decibels)
  };
}

function getDecibelDescription(db) {
  if (db < 30) return 'Very quiet (whisper)';
  if (db < 60) return 'Normal conversation';
  if (db < 90) return 'Loud (traffic)';
  return 'Very loud (potential hearing damage)';
}

console.log(calculateDecibels(1e-6));
// { decibels: '60.0', description: 'Normal conversation' }