In JavaScript, log() is a function that is used to return the natural logarithm of a number. Because the log() function is a static function of the Math object, it must be invoked through the placeholder object called Math.
Math.log(x)
x
- It represents the number whose logarithm have to be get.The log() function returns the natural logarithm of a number.
If the number is 0, the log() function will return -Infinity.
If the number is a negative value, the log() function will return NaN.
Let’s take a look at an example of how to use the log() function in JavaScript.
console.log(Math.log(1));
console.log(Math.log(2.5));
console.log(Math.log(0));
console.log(Math.log(-4));
Output
0
0.9162907318741551
-Infinity
NaN
In this example, the first output to the console log returned 0 which is the natural logarithm of 1.
The second output to the console log returned 0.9162907318741551 which is the natural logarithm of 2.5.
The third output to the console log returned -Infinity since the number provided was 0.
The fourth output to the console log returned NaN since the number provided was a negative value.
The Math.log() method cannot be used with complex arguments as only integer arguments are accepted.
console.log(Math.log(2+i));
Output
ReferenceError: i is not defined
The following example demonstrates that if null is passed as an argument, then this method returns negative infinity.
var a = null;
var b = "";
var c = [];
console.log(Math.log(a));
console.log(Math.log(b));
console.log(Math.log(c));
Output
Infinity
Infinity
Infinity
The following example demonstrates that if negative parameters are passed, this method returns NaN.
var a = -1;
var b = -2;
var c = Number.NEGATIVE_INFINITY;
console.log(Math.log(a));
console.log(Math.log(b));
console.log(Math.log(c));
Output
NaN
NaN
NaN
The following code example demonstrates that if the passed value is not a valid number, then the method returns NaN.
var a = "JavaScript";
var b;
console.log(Math.log(a));
console.log(Math.log(b));
Output
NaN
NaN
Thanks for reading !
#javascript #js #web_development