Related Articles

# JavaScript | Math.log2() function

• Last Updated : 19 Sep, 2021

The Math.log2() is an inbuilt function in JavaScript which give the value of base 2 logarithms of any number.
Syntax:

`Math.log2(p)`

Parameters: This function accepts a single parameter p which is any number whose base 2 logarithms is to be calculated.

Returns: It returns the value of base 2 logarithms of any number.

Examples:

```Input : Math.log2(5)

Output: 2.321928094887362```

Explanation:
Here value of bese 2 logarithms of number 5 is 2.321928094887362 as shown output.

```Input : Math.log2(10)
Output:3.321928094887362```

Let’s see some JavaScript code on this function:

• Example 1:

## Javascript

 `                   `

Output:

```9.965784284662087
3.584962500721156
4.700439718141092
2.321928094887362```
• Example 2:

## Javascript

 ``

Output:

```0
2
2.807354922057604
3.321928094887362
3.700439718141092
4
4.247927513443585```

Errors and exceptions: Parameters for this function should always be a number otherwise it returns NaN i.e, not a number when its parameter is taken as a string.

• Example 1:

## Javascript

 ``

Output:

`NaN`
• Example 2: This function gives error when its parameter taken as complex number because it accept only integer value as the parameter.

## Javascript

 ``

Output:

`Error: Invalid or unexpected token`

Application: Whenever we need the value of base 2 logarithms of any number that time we take the help of this function.Its value needed many times in mathematics problem.
Let’s see JavaScript code for this application:

• Example 1:

## Javascript

 `                   `

Output:

`3.807354922057604`

Supported Browsers: The browsers supported by JavaScript Math.log2() function are listed below:

• Internet Explorer
• Firefox
• Opera
• Safari

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up