Caesars Cipher's awkward null

Caesars Cipher's awkward null


Tell us what’s happening:

This function returns a null instead of “A” Why this is happening and how do i elude that error?

Your code so far

function rot13(str) {
  var map = ['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'];
  str = str.split("");
  for (var i = 0; i < str.length; i++) {
    var e = map.indexOf(str[i]);
    if (e > 13) {
      str[i] = map[e-13];
    } else if (e <= 13 && e > 0) {
      str[i] = map[e+13];
  return str;

rot13("SERR PBQR PNZC");

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0.

Link to the challenge:


.map is a prototype… not sure you can use it as a variable?


@marioxp97 Arrays are 0-indexed. ‘A’ is at index 0, but you never convert to it. When the index of the ciphertext is 13, you add 13 to it rarther than subtract. Adding 13 to 13 gives you 26, which is out of the bounds of the array. When you’re on 13 (‘N’) you need to subtract to get to ‘A’.

Also you need to join that array of characters back together at the end.

Note, just for readability/simplicity you can just do something like alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' then var e = alphabet.indexOf(str[i]), it doesn’t need to be an array, String has an indexOf method as well


.map is a function, but map is just a variable in the OPs code.


kewl ty Randell , i’m used to a diff language, and
am learning alot from this site :slight_smile:


Actually, it is undefined and not null. The FCC fake console shows null sometimes for undefined values. Anyway, the reason you get undefined instead of the letter ‘A’ is because when your for loop gets to i = 11, str[11] is ‘N’, so e is equal to map.indexOf(‘N’) which is 13. Since 13 is greater or equal to 13 AND 13 greater than 0, the following else if block of code executes:

str[i] = map[e+13];

So, since e is 13, you have map[26] which is undefined, because there are only 26 elements in map and arrays are zero-indexed.


I highly recommend you avoid using variable names that are names of JavaScript built-in methods. That can get confusing quickly.