Skip to content

Binary to decimal with JavaScript

Binary to decimal with javascript

Binary to decimal is a good example of math for beginners of JavaScript. Today we shall learn about one of the greatest method of JavaScript which is reduceRight(). This is similar to the reduce() method but it iterates from right to left for an array. Just like the classic for loop does when we decrease the counter value. Here is an example –

for( let i = 10; i >= 0; i-- ){
    //do the stuffs here
}

In the above example, we are using the for loop from 10 to 0. Similarly the reduceRight() method works. You can find more about the method here – Array.prototype.reduceRight() It’s a very powerful and easy method to work with.


Binary to decimal example

In this practical example, we will try to write a function for the binary to decimal conversion with this method. Here is a code snippet for the same.

Code snippet

//binary to decimal function
function binToDec(bin){
  
    //return if nothing entered
    if(!bin){
        console.log("no binary code entered")
        return
    }

    //return if more than 8 characters entered
    if(bin.length > 8){
        console.log("maximum 8 characters allowed")
        return
    }

    //conditions for the entered digits
    if( bin.match(/[^0-1]/) ){
      console.log('value contains invalid binary')
      return
    }

    //function with reduceRight method
    let theDec = bin.split('').reduceRight((acc, value, index, arr ) => {
        return acc + parseInt(value) * Math.pow( 2, arr.length -1 - index )
    }, 0)

    console.log(theDec)
    return theDec
}

//usage: binToDec("1001")

What it does

The code above does the following –

  • User can enter up to 8 binary digits in one input field.
  • User will be notified if anything other than a 0 or 1 is entered.
  • The results shows in a single output field containing the decimal (base 10) equivalent of the binary number that was entered.

Live example of binary to decimal with JavaScript

I have created a pen for live example purpose. You can check the codepen example here – Binary to decimal with “reduceRight” method

Same function with for loop

The method we have used in the binToDec() function is reduceRight(). However the same function can also be written in the classic for loop. Let me show you quickly –

//replace the reduceRight with for loop
let theDecNew = 0
for(let i = bin.length -1; i >= 0; i-- ){
    theDecNew += parseInt(bin[i]) * Math.pow( 2, bin.length -1 -i )
}

All about binary

Full description of the Binary – Binary number system


Leave a Reply