Caesar Cipher Project in JavaScript

I am having a hard time getting my code to pass. it seems like everything is coded right and it says what it is supposed to say in the terminal but when I run the code freecodecamp says it’s wrong. I’m confused.

function rot13(str) {
  const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

  let newStr = ' ';

  for(let i = 0; i < str.length; i++){
    let index = alphabet.indexOf(str[i]);
    if(index == -1){
      newStr += str[i];
    } else {
      let newIndex = (index + 13) % 26;
      newStr += alphabet[newIndex];
    }
  }

  return newStr;
}

console.log(rot13("SERR PBQR PNZC"));
console.log(rot13("SERR CVMMN!"));
console.log(rot13("SERR YBIR?"));
console.log(rot13("GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT."));

Why start with this here?

I’ve tried a few other ways to write out the problem but this will read right in the terminal but it will not pass the grader.

I am still trying to figure things out and the format also

Ok. I’m trying to help you fix your code.

So… why start with a string holding a single space as the newStr?

Not sure why I placed it there now. It looked right at the time but now that I look back at it I should have placed it somewhere else or not at all.

Maybe should have moved it under the let = index part

Right now your code say “start with a single space and add the new letters”. You have the right logic for finding the new letters, but starting with that extra space is causing a problem.

No, you can’t put it there. Then newStr would only live inside of the loop and couldn’t collect information from all loop iterations.

Should I just delete it?

You can’t just delete the newStr variable. Then you would have nowhere to put the new letters…

I have wrote out a few different codes but this seems the closest so far

function rot13(str) {
  const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

  let newStr = ' ';

  for(let i = 0; i < str.length; i++){
    let index = alphabet.indexOf(str[i]);
    if(index == -1){
      newStr += str[i];
    } else {
      let newIndex = (index + 13) % 26;
      newStr += alphabet[newIndex];
    }
  }

  return newStr;
}

console.log("***" + rot13("SERR PBQR PNZC") + "***");
console.log("***" + rot13("SERR CVMMN!") +  "***");
console.log("***" + rot13("SERR YBIR?") +  "***");
console.log("***" + rot13("GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.") +  "***");

Can you explain the asterisks? What they represent

What do you see when you run this code?

I stopped coding for awhile and just got back into it and feel stupid over half the time

This stuff is hard. Its ok to struggle.