JavaScript Math.log() Method



In JavaScript, the Math.log() method is used to calculate the natural logarithm (base e) of a number. The natural logarithm of a number x, denoted as ln(x), is the exponent to which the mathematical constant e (approximately equal to 2.71828) must be raised to obtain the value x.

If the provided argument is positive or negative 0, this method returns "-Infinity". If argument is less than 0, it returns NaN (Not a number).

Syntax

Following is the syntax of JavaScript Math.log() method −

 Math.log(x) 

Parameters

This method accepts only one parameter. The same is described below −

  • x: A numeric value.

Return value

This method returns the natural logarithm (base e) of the provided numeric expression.

Example 1

In the following example, we are using the JavaScript Math.log() method to calculate the natural logarithm of 10 −

 <html> <body> <script> const result = Math.log(10); document.write(result); </script> </body> </html> 

Output

After executing the above program, it returns approximately 2.3025.

Example 2

Here, we are calculating the natural logarithm of 1 −

 <html> <body> <script> const result = Math.log(1); document.write(result); </script> </body> </html> 

Output

The natural logarithm of 1 is 0 because e^0 equals 1.

Example 3

If the provided argument is 0 or -0, this method returns -Infinity as result −

 <html> <body> <script> const result1 = Math.log(0); const result2 = Math.log(-0); document.write(result1, <br>, result2); </script> </body> </html> 

Output

If we execute the program, it will return -Infinity.

Example 4

If the given argument is less than 0, this method returns NaN as result −

 <html> <body> <script> const result = Math.log(-1); document.write(result); </script> </body> </html> 

Output

Here, -1 is less than 0, thus it returned NaN as result.

Advertisements