Logarithmic Functions
You'll learn how to calculate logarithms in JavaScript using built-in Math methods for different bases.
What Are Logarithms?
A logarithm answers the question: "To what power must I raise a base to get this number?" For example, log₁₀(100) = 2 because 10² = 100. Think of logarithms as the inverse of exponentiation—if Math.pow(2, 3) equals 8, then the logarithm base 2 of 8 equals 3.
JavaScript's Logarithm Methods
JavaScript provides three built-in logarithm functions in the Math object:
Math.log() – Natural Logarithm (base e)
Math.log() calculates the natural logarithm, using Euler's number (e ≈ 2.718) as the base:
Math.log(Math.E); // 1 (because e¹ = e)
Math.log(10); // 2.302585... (e^2.303 ≈ 10)
Math.log(1); // 0 (because e⁰ = 1)
Math.log10() – Base-10 Logarithm
Math.log10() uses base 10, commonly used in science and engineering:
Math.log10(100); // 2 (because 10² = 100)
Math.log10(1000); // 3 (because 10³ = 1000)
Math.log10(10); // 1
Math.log2() – Base-2 Logarithm
Math.log2() uses base 2, essential for computer science and binary calculations:
Math.log2(8); // 3 (because 2³ = 8)
Math.log2(1024); // 10 (because 2¹⁰ = 1024)
Math.log2(2); // 1
Custom Base Logarithms
For other bases, use the change-of-base formula: log_b(x) = Math.log(x) / Math.log(b):
// Calculate log base 5 of 125
Math.log(125) / Math.log(5); // 3 (because 5³ = 125)
Key Takeaway: JavaScript provides Math.log() (natural), Math.log10() (base-10), and Math.log2() (base-2) for logarithmic calculations; use the change-of-base formula for other bases.