Search code examples
javascriptbinaryundefinedstring-concatenation

How to declare a variable with no value?


The following code is what I am using to convert a hex to binary. To print binary out, I add individual strings to a previously declared blank variable. However, this prints out "undefined + binary". Is there a way to declare a variable with no value --even undefined. If not is there a better way to concatenate variables in a for loop without a previously declared variable?

All help will be appreciated!

        var integer = prompt("Insert hex digit");
        var userHexDigits = [];
        var hexDigits = [0, 1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f'];
        var binaryDigits = ['0000', '0001','0010','0011', '0100','0101','0110','0111','1000','1001','1010','1011','1100','1101','1110','1111'];
        var hexy = [];
        var binary 

        for(i = 0; i < integer.length; i++) {
            digit = i + 1;
            document.write("Your digit #" + digit + " is:  " + integer[i] + "<br/>");
            userHexDigits.push(integer[i]);
        }

        for (var m = 0; m < userHexDigits.length; m++) {
            hex = userHexDigits[m];

            for(k =0; k < hexDigits.length; k++) {
                if (hex == hexDigits[k]){
                    binary += binaryDigits[k] + " ";
                }
            }

        }

        document.write("<br/><br/>The number " + integer + " in binary is " + binary);

Solution

  • If you want a string variable with an empty value just:

    var binary = "";