JavaScript program to take in a binary number as a string and returns its numerical equivalent in base 10

We are required to write a JavaScript function that takes in a binary number as a string and returns its numerical equivalent in base 10. Therefore, let's write the code for the function.

This one is quite simple, we iterate over the string using a for loop and for each passing bit, we double the number with adding the current bit value to it like this ?

Example

const binaryToDecimal = binaryStr => {
   let num = 0;
   for(let i = 0; i 

Output

The output in the console will be ?

13
104
21

How It Works

The algorithm processes each binary digit from left to right. For each digit, it doubles the current result (equivalent to left-shifting in binary) and adds the digit value (0 or 1). This effectively builds the decimal value bit by bit.

Using Built-in parseInt() Method

JavaScript provides a built-in method to convert binary strings to decimal using parseInt() with base 2:

const binaryToDecimalBuiltIn = binaryStr => {
   return parseInt(binaryStr, 2);
};

console.log(binaryToDecimalBuiltIn('1101'));
console.log(binaryToDecimalBuiltIn('1101000'));
console.log(binaryToDecimalBuiltIn('10101'));
13
104
21

Comparison

Method Readability Performance Learning Value
Manual Loop Moderate Good High
parseInt() High Optimized Low

Conclusion

Both methods effectively convert binary strings to decimal. The manual approach helps understand the conversion process, while parseInt() provides a cleaner, production-ready solution.

Updated on: 2026-03-15T23:18:59+05:30

304 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements