JavaScript Math.log2()
Syntax & Examples


Math.log2() static-method

The Math.log2() method in JavaScript returns the base-2 logarithm of a number. This logarithm is the power to which the number 2 must be raised to obtain the value of the input number. It is a static method of Math, meaning it is always used as Math.log2() and not as a method of a Math object created (Math is not a constructor).


Syntax of Math.log2()

The syntax of Math.log2() static-method is:

Math.log2(x)

This log2() static-method of Math returns the base-2 logarithm of x.

Parameters

ParameterOptional/RequiredDescription
xrequiredA number for which to return the base-2 logarithm.

Return Type

Math.log2() returns value of type Number.



✐ Examples

1 Using Math.log2() with a positive number

In this example, we use the Math.log2() method to find the base-2 logarithm of 8.

For example,

  1. We call Math.log2() with 8 as the argument.
  2. The method returns the base-2 logarithm of 8.
  3. We log the result to the console using console.log().

JavaScript Program

console.log(Math.log2(8));

Output

3

2 Using Math.log2() with 1

In this example, we use the Math.log2() method to find the base-2 logarithm of 1.

For example,

  1. We call Math.log2() with 1 as the argument.
  2. The method returns the base-2 logarithm of 1, which is 0.
  3. We log the result to the console using console.log().

JavaScript Program

console.log(Math.log2(1));

Output

0

Summary

In this JavaScript tutorial, we learned about log2() static-method of Math: the syntax and few working examples with output and detailed explanation for each example.