My Caesar Cipher works, but won't pass the tests

My Caesar Cipher works, but won't pass the tests
0

#1
var wrdStr;
var newStr = [];
var key13;
function rot13(str) { // LBH QVQ VG!
  str = str.split(" ");
  for(var i = 0; i < str.length; i++){
    wrdStr = str[i].split('');
    console.log(wrdStr);
    for(var j = 0; j < wrdStr.length; j++){
      key13 = wrdStr[j].charCodeAt(0);
      if (key13 >= 65 && key13 <= 91) {
        key13 = key13 - 13;
        if (key13 < 65){
          key13 = key13 + 26;
        }
      }
      wrdStr[j] = String.fromCharCode(key13);
    }
    wrdStr = wrdStr.join(''); 
    newStr.push(wrdStr);
  }
  str = newStr.join(' ');
  console.log(str);
  return str;
}

#2

Move the globally declared variables

  var wrdStr;
  var newStr = [];
  var key13;

inside the rot13 function.


#3

You are using global variables.

Global variables persist after function calls have completed, so we have to be very careful about modifying globals in functions. Your code relies on wrdStr being undefined and newStr being an empty array when the function is called, but after rot13 has been executed, this is not the case. This means that your function will only work once.


#4

Thanks, that makes a lot of sense. I thought I was helping myself out by making the variables global, but now I see why that doesn’t work in this case.