JavaScript Math.log2() Method
- Syntax of JavaScript
Math.log2(): - Example Code: Use the
Math.log2()Method to Find the Base 2 Logarithm of Positive Values - Example Code: Use the
Math.log2()Method to Find the Base 2 Logarithm of Negative Values - Example Code: Use the
Math.log2()Method With Infinity Values - Example Code: Use the
Math.log2()Method With 0 and 1 Values
We can use the Math.log2() method of the JavaScript Math library to find the base 2 logarithm of a number. In short, the Math.log2() method calculates the log2(number).
Syntax of JavaScript Math.log2():
let value = Math.log2(number) Parameters
number | This is the value to be evaluated. |
Return
The Math.log2(number) method returns the base 2 logarithm of number.
Example Code: Use the Math.log2() Method to Find the Base 2 Logarithm of Positive Values
We can use the Math.log2(number) method to find the logarithm of a number, given base 2. We have taken different positive values in the example below and found its logarithm base 2 using the Math.log2(number) method.
The output shows that the method returns the negative output value when we take a number between 0 and 1.
let num1 = Math.log2(10); let num2 = Math.log2(1.324); let num3 = Math.log2(0.321); console.log(num1); console.log(num2); console.log(num3); Output:
3.321928094887362 0.40490312214513074 -1.639354797539784 Example Code: Use the Math.log2() Method to Find the Base 2 Logarithm of Negative Values
Here, we have taken the different negative values as the number parameter of the Math.log2(number) method. When we try to find the logarithm of negative numbers in JavaScript, it always returns the NaN value, which users can see in the output.
let value1 = Math.log2(-20); let value2 = Math.log2(-5.23); let value3 = Math.log2(-0.421); console.log(value1); console.log(value2); console.log(value3); Output:
NaN NaN NaN Example Code: Use the Math.log2() Method With Infinity Values
In this section, we have used the Infinity and -Infinity values as the number values. As Infinity is the positive value, Math.log2(Infinity) returns the positive Infinity, and as -Infinity is a negative value, the method returns the NaN value.
let value1 = Math.log2(Infinity); let value2 = Math.log2(-Infinity); console.log(value1); console.log(value2); Output:
Infinity NaN Example Code: Use the Math.log2() Method With 0 and 1 Values
In this example, we have used the Math.log2(number) method with the 0 and 1 values. For the 0, the method returns the -Infinity output, and for the 1 method returns the 0 output value.
let number1 = Math.log2(0); let number2 = Math.log2(1); console.log(number1); console.log(number2); Output:
-Infinity 0 The Math.log2() method is compatible with all modern browsers.
