Skip to content
Blog

Binary to Decimal in JavaScript (With Code)

By Published A short read

     Hi everyone in this article we going to make a function to convert binary numbers into decimal numbers.

Prefer to watch? Here's the video version of this post.

    So before that make sure you are know how to convert the binary numbers to decimal on papers in traditional way. And over here we are just going to implement that logic into code. 

    And the language is javascript but the logic can be implemented in any language you want. And we are using node.js as javascript runtime.

Binary to Decimal In Javascript

    code: 

const toDecimal = (binaryNumber) => {
    const digits = String(binaryNumber).split("").reverse()
    let sum = 0
    let counter = 1
    digits.forEach(e => {
        if(Number(e) !== 0) sum = sum + counter
        counter = counter * 2
    })
    return sum
}
console.log(toDecimal(0))
console.log(toDecimal(10))
console.log(toDecimal(11010))
console.log(toDecimal(1001))
console.log(toDecimal(101))

    output: 

$ node index.js
0
2
26
9
5

Thankyou :)