The Math.log()
method returns the natural logarithm of a number. It is equivalent to ln(x) in mathematics.
Example
// calculate the log base e of 1
var value = Math.log(1);
console.log(value);
// Output: 0
log() Syntax
The syntax of log()
is:
Math.log(x)
Here, log()
is a static method. Hence, we need to access the method using the class name, Math
.
log() Parameter
The log()
method takes in:
- x - a number
log() Return Values
The log()
method returns:
- the base e logarithm of the given number.
NaN
for negative numbers and non-numeric arguments.
Example 1: JavaScript Math.log()
// find the base e log value of 1
var value1 = Math.log(1);
console.log(value1);
// find the base e log value of 10
var value2=Math.log(10);
console.log(value2)
// find the base e log value of 8
var value3 = Math.log(8);
console.log(value3);
Output
0 2.302585092994046 2.0794415416798357
In the above example,
Math.log(1)
- computes the base e log value of 1Math.log(10)
- computes the base e log value of 10Math.log(8)
- computes the base e log value of 8
Example 2: log() With 0
// find the base e log value of 0
var value = Math.log(0);
console.log(value);
// Output: -Infinity
In the above example, we have used the log()
method to compute the base e log value of 0.
The output -Infinity
indicates that the base e log value of 0 is negative infinity.
Example 3: log() With Negative Values
// find the base e log value of -1
var value = Math.log(-1);
console.log(value);
// Output: NaN
In the above example, we have used the log()
method to compute the base e log value of the negative number -1.
The output NaN
stands for Not a Number. We get this result because the base e log value of negative numbers is undefined.
Example 4: log() With Euler's Constant e
// log() with Euler's constant e
var value = Math.log(Math.E);
console.log(value);
// Output: 1
In the above example, we have used the log()
method to compute the base e log value of Math.E
(Euler's constant e).
The output 1
indicates that the base e log value of e is 1 i.e. ln(e) = 1.
Also Read: