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
}
Top comments (4)
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)
:Thanks for sharing! I didn't even consider doing that
That is a cool function! I don't have an answer for you. Surely MDN has an article on that?
Unfortunately the MDN page is pretty sparse. But someone above suggested looking at the JS specs