JavaScript function to convert decimal number to binary I was recently asked this in an interview for a front-end position and I came up with something like the code below, which seems to work but is clunky.  (Number.toString() was not allowed.)

function convertBinary(number) {
  var n = 0;
  var binaryArr = [];

  var difference = Math.pow(2, n);

  //find out how many digits are needed
  while (difference &lt;= number){
    n++;
    difference = Math.pow(2, n);
    binaryArr.push(0);
  }

  n--;

  while(number &gt; 0) {
    if (Math.pow(2, n) &lt;= number) {
      binaryArr[n] = 1;
      number-= Math.pow(2, n);
    }
    n--;
  }

  return binaryArr.reverse().join("") * 1
}


Also I was asked what the Big(o) of this was but had a hard time figuring it out— what is the time complexity of JavaScript reverse?
Strictly speaking, the number parameter isn't decimal; it's just an abstract number.  (This is more a criticism of the terminology in your question title than of your code.)  On the other hand, it is very weird that you coerce the result into a number (101010) rather than returning it as a string ('101010').

The implementation strategy, using Math.pow(…, 2), strikes me as extravagant.  You should be able to do this more efficiently using just arithmetic:

function convertBinary(number) {
    var binaryArr = [];
    for (; number; number /= 2) {
        binaryArr.push(number % 2);
    }
    return binaryArr.reverse().join('');
}


… or the same thing using bitwise operations:

function convertBinary(number) {
    var binaryArr = [];
    for (; number; number &gt;&gt;= 1) {
        binaryArr.push(number &amp; 1);
    }
    return binaryArr.reverse().join('');
}