Https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/caesars-cipher/

Https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/caesars-cipher/
0

#1

This code works. When I saw the solutions, the basic solution had the string converted to an array.

I would appreciate if someone could please explain why this wouldn’t be a good approach, and what are the shortcomings here. My code is :



function rot13(str) { // LBH QVQ VG!
 let initial=0;
 let shifted = 0;
 let i = 0;
 let str2='';
 for ( i= 0; i<str.length;i++){
   initial = str.charCodeAt(i);
   console.log(initial);
   if (initial <65 || initial>90){
     shifted = initial;
   }
   else if (initial >= 78) {
     shifted = 65 +(initial-78);
   }
   else{
     shifted = initial +13;
   }
   str2+= String.fromCharCode(shifted);
 }
  return str2;
}

// 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 a forum post, please precede it with a separate line of three backticks and follow it with a separate 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.

Note: Backticks are not single quotes.


#3

Just because it is not one of the solutions shown in the Guide, does not mean it is not a good solution. The only recommendation I would make is only initializing the str2 variable in the beginning. The other three variables (shifted, initial and i) can be declared when first used in your code. For example, initial would be initialized inside the for loop, because that is the only place it is used, shifted would just be declared in the for loop, and i should be initialized in the for statement.