เปลี่ยนจาก int เป็น binary string

How do I convert an integer to binary in JavaScript?

เช่น ป้อน 10 จะได้ 00001010

<!DOCTYPE html>
<html>

<body>
    <script>
        function BinaryPad(x) {
            var i = 0;
            var binaryvar = " ";

            function add(n) {
                if (n == 0) {
                    binaryvar = "0" + binaryvar;
                }
                else {
                    binaryvar = "1" + binaryvar;
                }
            }

            function binary() {
                while (i < 1) {
                    if (x == 0) {
                        add(0);
                        return binaryvar;
                    } else if (x == 1) {
                        add(1);
                        //document.write(binaryvar);
                        return binaryvar;
                        //break;
                    }
                    else {
                        if (x % 2 == 0) {
                            x = x / 2;
                            add(0);
                        }
                        else {
                            x = (x - 1) / 2;
                            add(1);
                        }
                    }
                }
            }

            binaryvar = binary(); // unpad binary
            //document.write("<p>" + binaryvar + "</p>");
            var k = binaryvar.length;
            for (var i = k; i <= 8; i++) {
                binaryvar = "0" + binaryvar;
            }
            //document.write(binaryvar); // pad binary
            return binaryvar;
        }

        document.write(BinaryPad(10));
    </script>

</body>

</html>