For Loop - Help Understanding / Caesars Cipher Basic Algorithm

For Loop - Help Understanding / Caesars Cipher Basic Algorithm
0

#1

Hi,

I am solving the last algorithm (Caesars Cipher) for the Basic Java course and need some help understanding where my code has gone wrong. I was able to convert the value of the first character 13 places back but I am having trouble getting the for loop to return the whole converted string. My loop only returns the first letter converted.

Can anyone help with an explanation on what I’m doing wrong and what I should take a look at - or if the way i’m going about is completely wrong.

CODE BELOW

function rot13(str) { // LBH QVQ VG!
   
  str.split("");
  var letsCount = "";
  for (var i = 0, len = str.length; i < len; i++) {
    letsCount = str[i];
    var ourChar = letsCount.charCodeAt();
    ourChar -= 13;
    var letters = String.fromCharCode(ourChar);
    return letters;
  } 
}

// Change the inputs below to test
rot13("SERR PBQR PNZC");

#2

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

The reason your solution only returns the first converted character, is because you put the following return statement inside your for loop.

return letters;

Your solution only makes it one iteration through the for loop, before returning letters. Once a return statement is executed, the function is exited and returns the value specified even if the for loop has not completed.