The Math.log2() method returns the base 2 logarithm of a number. It is equivalent to log2(x) in mathematics.
Example
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.
NaNfor negative numbers and non-numeric arguments.
Example 1: JavaScript Math.log2()
Output
0 3
In the above example,
Math.log2(1)- computes the base 2 log value of 1Math.log2(8)- computes the base 2 log value of 8
Example 2: log2() With 0
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
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: