# JavaScript: Convert a binary number to a decimal number

## JavaScript Math: Exercise-2 with Solution

Write a JavaScript function to convert a binary number to a decimal number.

Test Data: console.log(bin_to_dec('110011')); console.log(bin_to_dec('100')); 51 4

Pictorial Presentation:

Sample Solution:-

HTML Code:

``````<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>Binary number to a decimal number</title>
<body>

</body>
</html>
```
```

JavaScript Code:

``````function bin_to_dec(bstr) {
return parseInt((bstr + '')
.replace(/[^01]/gi, ''), 2);
}
console.log(bin_to_dec('110011'));
console.log(bin_to_dec('100'));
```
```

Sample Output:

```51
4
```

Flowchart:

Live Demo:

See the Pen javascript-math-exercise-2 by w3resource (@w3resource) on CodePen.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿

## JavaScript: Tips of the Day

arrow function

```const user = {
email: "[email protected]",
updateEmail: email => {
this.email = email
}
}

user.updateEmail("[email protected]")
console.log(user.email)
```

The updateEmail function is an arrow function, and is not bound to the user object. This means that the this keyword is not referring to the user object, but refers to the global scope in this case. The value of email within the user object does not get updated. When logging the value of user.email, the original value of [email protected] gets returned.

Ref: https://bit.ly/2IUFeTa