Caesars Cipher - Double For Loop Help

Tell us what’s happening:
Trying to create an if statement within a for loop and another for loop within else statement. The code works for one letter strings, but fails to loop back through remaining string.

How can I get for loop to continue to iterate through str after completing if statment?

I realize there is probably a much easier way and more convention way to achieve the same results, but I am trying to write the code all by myself without looking at the hints provided and this is what I thought of. I can write it with while loop inside a for loop as well.

Your code so far


function rot13(str) { // LBH QVQ VG!
let preLetters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
let rot13Letters = ['N', 'O', 'P', 'Q', 'S', 'T', 'U', 'V', 'W', 'X', 'Y','Z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'];

let caesarCipher = '';

for (let i=0; i <= str.length; i++){
  if (str[i] === /\W/gi){
      return caesarCipher += str[i];
    }
  else {
  for (let j=0; j<preLetters.length; j++){
    while (str[i] === preLetters[j]){
      return caesarCipher += rot13Letters[j];
}}}}
return caesarCipher;
}


// Change the inputs below to test
console.log(rot13("ABC"));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/caesars-cipher/

Remember when a return statement is executed, the function is exited. Inside your for loop, when the if statement condition evaluates to true, you are concatenating str[i] to caesarCipher and then returning its value.

What do you want to happen when the if statement evaluates to true?

Another more important question is what do you think the following code is checking?

I think you need to try and write out (in plain language) what you think the algorithm needs to be before writing any further code. You can write your algorithm in pseudo-code if you want, but mainly try to express what you expect certain sections to do and the conditions and decisions being made at the various steps.

One last thing that is not helping your solution, is the fact that there is one less element in the rot13Letters array than the preLetters array.

I didn’t realize that a return statement results in the function being exited! Thank you! I figured out the double loop now!

The if statement is still not working though. If the str iteration strict matches the regex for non-alphanumerical characters then add str iteration to caesarCipher.

Code is now working! Thank you for your help :slight_smile: