Favorites

JavaScript Math.log2() Method

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee
Math.log2()
JavaScript Math Static methodThis method is supported by all modern browsers.
Updated 28th November 2026

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

console.log(Math.log2(8));
console.log(Math.log2(1024));
console.log(Math.ceil(Math.log2(300)), 'bits for 300 values');

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.

This method is supported by all modern browsers.

Desktop

Chrome
Edge
Firefox
Opera
Safari

Tablets & Mobile

Chrome Android
Firefox Android
Opera Android
Safari iOS
Samsung Internet
Android WebView
-
Supported Unknown Not supported
☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee