Decimal number to binary number conversion in JavaScript I made this decimal to binary conversion as an exercise for myself and because it is obviously often asked during job interviews / tests.

Any hints concerning possible improvements welcomed.



// -- START : Testing the function --------
var display = document.querySelector('div');
var result = '';
var n = 255;
var maxSpace = n.toString().length;

// Assigning wrong parameter.
console.log('Result empty: ' + getBinaryNumber());
console.log('Result string: ' + getBinaryNumber('abc'));

// Helper function: Avoiding "stairs".
function getSpaces(count, someChar) {
  
  if (!count) return '';
  
  var ret = '';
  
  for (var i = 0; i &lt; count; i++) {
    ret += someChar;
  }
  
  return ret;
}

var spaces = getSpaces(maxSpace, '0');

for (var i = 0; i &lt;= n; i++) {
  result += 
    (spaces + i).slice(- maxSpace) + 
    ' : ' + getBinaryNumber(i, ' ') + '&lt;br /&gt;';
}

display.innerHTML = result;
// -- END : Testing the function --------

// Converts a decimal number to a binary number.

// -- Parameter --------------------------
// Number - The decimal number to convert.

// -- Return -----------------------------
// String - The number in it's binary
// represention.
// On error: 
// Returns an empty string.

function getBinaryNumber (decimalNumber, separator) {
  // Parameter check
  if (decimalNumber === 0) return 0;
  
  if (!decimalNumber) return '';
  
  if (isNaN(decimalNumber)) return '';
  
  separator = separator || '';
  // Local variables
  var ret = [];
  var bit = decimalNumber % 2; 
  
  ret.push(bit);
  
  decimalNumber = ~~(decimalNumber / 2);
  
  while (decimalNumber &gt; 1) {
    bit = decimalNumber % 2; 
    ret.push(bit);
    
    decimalNumber = ~~(decimalNumber / 2);
  }
  
  if (decimalNumber &gt; 0) ret.push(decimalNumber);
  
  return ret.reverse().join(separator);
}
&lt;div&gt;&lt;/div&gt;
Comment says, that function will return a string, and then returns a number.

if (decimalNumber === 0) return 0


Best improvement would be using a native method

function getBinaryNumber(num, sep) {
    if (typeof num != "number") num = parseFloat(num)
    return sep ? num.toString(2).split("").join(sep) : num.toString(2)
}


I would remove separator parameter, as it makes no sense to combine this functionality.

function getBinaryNumber(num) {
    return (typeof num == "number" ? num : parseFloat(num)).toString(2)
}