DEV Community

Jasterix
Jasterix

Posted on

What is happening under the hood when you use toString(2) in JavaScript?

I recently reviewed JavaScript base conversations and came across the .toString(base) method. While it is useful, I don't quite understand what is actually happening under the hood with this method.

Below is a quick function I wrote to convert a decimal number to binary. Is JavaScript essentially doing the same thing or something else?

function toBinary(n){
    let bin = []

    while(n > 0){
        if (n%2==0){
            bin.push(0)
            n = n/2
        } else {
            n = n-1
            bin.push(1)
        }
    }
    return bin
}
Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
hbgl profile image
hbgl

The specification says that the result of toString(radix) with radix != 10 is implementation dependent. Nevertheless, I assume that result should be pretty consistent across runtimes.

If you really want to know what happens under the hood, then you need to look at the source code of actual JavaScript runtimes. The nice thing is that many of them are open source. Here are some implementations of toString(radix):

Collapse
 
jasterix profile image
Jasterix

Thanks for sharing! I didn't even consider doing that

Collapse
 
cwraytech profile image
Christopher Wray

That is a cool function! I don't have an answer for you. Surely MDN has an article on that?

Collapse
 
jasterix profile image
Jasterix

Unfortunately the MDN page is pretty sparse. But someone above suggested looking at the JS specs