JavaScript Math log2()

In this tutorial, you will learn about the JavaScript Math.log2() method with the help of examples.

The Math.log2() method returns the base 2 logarithm of a number. It is equivalent to log2(x) in mathematics.

Example

// calculate the base 2 log of 2 let value= Math.log2(2);
console.log(value) // Output: 1

log2() Syntax

The syntax of log2() is:

Math.log2(x)

Here, log2() is a static method. Hence, we need to access the method using the class name, Math.


log2() Parameters

The log2() method takes in:

  • x - a number

log2() Return Values

The log2() method returns:

  • the base 2 logarithm of the given number.
  • NaN for negative numbers and non-numeric arguments.

Example 1: JavaScript Math.log2()

// find the base 2 log value of 1 var value1 = Math.log2(1);
console.log(value1);
// find the base 2 log value of 8 var value2=Math.log2(8);
console.log(value2)

Output

0
3

In the above example,

  • Math.log2(1) - computes the base 2 log value of 1
  • Math.log2(8) - computes the base 2 log value of 8

Example 2: log2() With 0

 
// find the base 2 log value of 0 var value = Math.log2(0);
console.log(value); // Output: -Infinity

In the above example, we have used the log2() method to compute the base 2 log value of 0.

The output -Infinity indicates that the base 2 log value of 0 is negative infinity.


Example 3: log2() With Negative Values

// find the base 2 log value of -1 var value = Math.log2(-1);
console.log(value); // Output: NaN

In the above example, we have used the log2() method to compute the base 2 log value of a negative number.

The output NaN stands for Not a Number. We get this result because the base 2 log value of negative numbers is undefined.


Recommended Readings:

Did you find this article helpful?