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

Jasterix - Feb 1 '21 - - Dev Community

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
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player