The code return the correct result but still can't pass the challenge


#1

Hey, everyone. I’m stuck at Binary Agents Algorithm Challenge. Not sure if my code is wrong, I can’t pass the test. Even though my code returns the correct result. Any advice?

var letters = [];

function toLetter(bits) {
  var j = 0;
  var currValue;
  var charCode = 0;
  for(var i = 7; i >= 0; i--) {
    currValue = Math.pow(2, i) * bits[j];
    j++;
    charCode += currValue;
  }
  var letter = String.fromCharCode(charCode);
  letters.push(letter);
}

function binaryAgent(str) {
  var binary = str.split(" ");
  binary.forEach(function(el) {
    toLetter(el);
  }); 
  return letters.join('');
}


binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");

#2

Most likely it’s because you’re using a global variable (letters). When FCC runs multiple tests the letters array doesn’t get reset, so your first test may look like it passes but the next ones won’t.

You should refactor your code so that you use no global variables, it’s good practice to do that in general anyways. Only challenge I’m aware of that needs to use a global variable was Counting Cards.


#3

Hey, thank you. It works now.
I create the letters array in binaryAgent() function and passing it in the toLetter() function.