Questions about the Caesars Cipher

Tell us what’s happening:
I think my answer is similar to the suggested answer but why cant it returns the same answer??

Your code so far

function rot13(str) {
 var a = str.split("");
var answer = [];

for(var i=0; i< a.length; i++){
if(str.charCodeAt(a[i])<65 || str.charCodeAt(a[i])>90 ){
}else if(str.charCodeAt(a[i])<78){
 str.charCodeAt(a[i])+ 13;
answer.push(String.fromCharCode(str.charCodeAt(a[i])+ 13));
}else  {
  str.charCodeAt(a[i])- 13;
 answer.push(String.fromCharCode(str.charCodeAt(a[i])- 13));


 return answer.join("");

console.log(rot13("SERR PBQR PNZC"));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.2 Safari/605.1.15.

Challenge: Caesars Cipher

Link to the challenge:

It looks like you have a couple of issues going on, and you’re also doing a lot more work than you need to do.

The first issue is, when you use charCodeAt, the parameter you pass should be a position index. Since the string is only 14 characters long, this would be a number from 0 to 13. But instead, you are passing a[i], which is the character at that position . (For example, in the first iteration of the loop, you would have “str.charCodeAt(‘S’)” I’m not really sure what this does, but it’s not what you want.

You also have a misspelling fromCharCOde in one place (extra capital letter).

The extra work, is that you really don’t need to split the string into an array, since you are calling str.charCodeAt in any case. You also have some extra lines that don’t actually do anything (the first line in the else if block, and the first line in the else block.

Once you clean those up, everything should work… :slight_smile:

Happy New Year!

THANKS!!! U HELP ME A lot. I think I do not so understand the concept of different functions. So I do a lot of wrong things.

I’m glad it was helpful! Believe me, everyone goes through that stage of making errors. Eventually you get it out of your system (until you start learning the next thing…) Good luck!