JavaScript Math.log2() Method
The Math.log2() static method returns the base-2 logarithm of a number.
Description
The Math.log2() static method returns the base-2 logarithm of a number. It tells you how many bits are needed for a value, or how many times a number can be halved.
For exact powers of two the result is a whole number, so Number.isInteger(Math.log2(n)) is a quick way to check whether a positive number is a power of two. It returns -Infinity for 0 and NaN for negative numbers.
Base-2 logarithms come up in computing, such as working out the depth of a binary tree or the number of times a search can halve a list. Like every member of Math, it's called on the Math object itself rather than on a number, and it only works with the Number type: passing a BigInt throws a TypeError.
Syntax
Math.log2(x)Parameters
- xA number.
Return Value
The base-2 logarithm of x.
Example
Browser Support
The following information will show you the current browser support for the Math.log2() method. Hover over a browser icon to see the version that first introduced support for this method.
Desktop





Tablets & Mobile





