totn JavaScript

JavaScript: Math log() function

This JavaScript tutorial explains how to use the math function called log() with syntax and examples.

Description

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.

Syntax

In JavaScript, the syntax for the log() function is:

Math.log(number);

Parameters or Arguments

number
The number to use in the calculation. It must be a value that is greater than 0.

Returns

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.

Note

  • Math is a placeholder object that contains mathematical functions and constants of which log() is one of these functions.

Example

Let's take a look at an example of how to use the log() function in JavaScript.

For example:

console.log(Math.log(1));
console.log(Math.log(2.5));
console.log(Math.log(0));
console.log(Math.log(-4));

In this example, we have invoked the log() function using the Math class.

We have written the output of the log() function to the web browser console log, for demonstration purposes, to show what the log() function returns.

The following will be output to the web browser console log:

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 second output to the console log returned -Infinity since the number provided was 0.

The second output to the console log returned NaN since the number provided was a negative value.