JavaScript Math.log2() Method



The JavaScript Math.log2() method accepts a numeric value as an argument and returns the base 2 logarithm of that number. Mathematically, the base 2 logarithm of a number x is the power to which the base (which is 2 in this case) must be raised to obtain the value x. In other words, if y = Math.log2(x), then 2^y = x.

The provided argument should be greater than or equal to 0 else, this method returns NaN (Not a number) as result.

Syntax

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

Math.log2(x)

Parameters

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

  • x: A positive number.

Return value

This method returns the base-2 logarithm of the specified number x.

Example 1

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

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

Output

After executing the above program, it returns 3.3219 as result.

Example 2

In here, we are retrieving the base 2 logarithm of numeric value 1 −

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

Output

It returns 0 as base 2 logarithm of 1.

Example 3

If we provide 0 or -0 as arguments to this method, it returns -Infinity as result −

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

Output

As we can see in the output, it returned -Infinity as result.

Example 4

If the provided argument is less than or equal to -1, this method returns NaN as result −

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

Output

As we can see in the output, it returned NaN as result.