Javascript: A byte is supposed to be 8 bits

The reason why .toString(2) does not produce an 8-bit representation of a number is that toString works for more numbers than just 0 through 255. For example:

(1).toString(2) ==> "1"
(2).toString(2) ==> "10"
(3).toString(2) ==> "11"
(4).toString(2) ==> "100"
(25).toString(2) ==> "11001"
(934534534).toString(2) => "110111101100111101110110000110"

So what JavaScript is doing with toString(2) is simply giving you numbers in base 2, namely 0, 1, 10, 11, 100, 101, etc., the same way that in base 10 we write our numbers 0, 1, 2, 3, 4, 5, ... and we don't always pad out our numbers to make a certain number of digits. That is why you are not seeing 8 binary digits in your output.

Now, the problem you have in mind is "how do I take a number in the range 0..255 and show it as a binary-encoded BYTE in JavaScript? It turns out that needs to be done by the programmer; it is not a built-in operation in JavaScript! Writing a number in base-2, and writing an 8-bit, are related problems, but they are different.

To do what you would like to, you can write a function:

function byteString(n) {
  if (n < 0 || n > 255 || n % 1 !== 0) {
      throw new Error(n + " does not fit in a byte");
  }
  return ("000000000" + n.toString(2)).substr(-8)
}

Here is how it can be used:

> byteString(-4)
Error: -4 does not fit in a byte
> byteString(0)
'00000000'
> byteString(7)
'00000111'
> byteString(255)
'11111111'
> byteString(256)
Error: 256 does not fit in a byte