The JavaScript log2() function is a math method that returns the base 2 logarithm of a given positive number greater than 0. The syntax of the log2() function is
Math.log2(n)
Parameter: A positive number that is greater than 0.
Return value: It returns the base 2 logarithmic value of a given number. If we pass a negative number, it returns NaN.
JavaScript log2 example
In the following example, we use the Math.log2() function to find the base 2 logarithm of various positive integer numbers. For more functions, please refer to the Math methods article from JavaScript.
console.log(Math.log2(10));
console.log(Math.log2(100));
console.log(Math.log2(1000));
console.log(Math.log2(5500));
3.321928094887362
6.643856189774724
9.965784284662087
12.425215903299385
Example 2: If we use positive or negative 0 as the Math.log2() function argument, it returns -Infinity as the output.
console.log(Math.log2(0));
console.log(Math.log2(-0));
-Infinity
-Infinity
TIP: Use log() for natural logarithmic value and base 10 log value, use the log10 function.
Example 3: If we pass a positive infinity, the JavaScript Math.log2() returns the same result. However, if we pass -Infinity or NaN as the parameter, it returns NaN as the output.
console.log(Math.log2(Infinity));
console.log(Math.log2(-Infinity));
console.log(Math.log2(NaN));
Infinity
NaN
NaN
Example 4: If we pass a string number, the Math.log2() function returns the base 2 logarithm value., However, if it can’t convert it to a number, it returns NaN.
console.log(Math.log2("1500"));
console.log(Math.log2("2500"));
console.log(Math.log2("hi"));
10.550746785383243
11.287712379549449
NaN
Related Math Posts