JavaScript Tutorial JavaScript References

JavaScript - Math.log2() Method



The JavaScript Math.log2() method returns the base-2 logarithm of a given number.

Syntax

Math.log2(x)

Parameters

x Specify the number.

Return Value

Returns the base-2 logarithm of a given number.
If the x is negative, it returns NaN.
If the x is 0, it returns -Infinity.

Example:

In the example below, Math.log2() method is used to calculate the base-2 logarithm of a given number.

var txt;

txt = "Math.log2(1) = " + Math.log2(1) + "<br>";
txt = txt + "Math.log2(2) = " + Math.log2(2) + "<br>";
txt = txt + "Math.log2(10) = " + Math.log2(10) + "<br>";
txt = txt + "Math.log2(0) = " + Math.log2(0) + "<br>";
txt = txt + "Math.log2(-1) = " + Math.log2(-1) + "<br>";

The output (value of txt) after running above script will be:

Math.log2(1) = 0
Math.log2(2) = 1
Math.log2(10) = 3.321928094887362
Math.log2(0) = -Infinity
Math.log2(-1) = NaN

❮ JavaScript - Math Object

5