Can someone please explain the math here? I'm a little lost

Tell us what’s happening:
So I am on the JavaScript Algorithms and Data Structures Projects: Caesars Cipher challenge, I seem to have figured it all out, apart from the final " shifting by 13 places" part of the code.

In my mind, it seems simple, get the ASCII code, substract 13, then back to string, but when I do this, I don’t get the desired result. So I google it, and it seems the solution is actually not to subtract 13 but instead "- 65 + 13) % 26) + 65

What!

I used this code and it worked, but why oh why. Why subtract 65, and then add 13?
what is the purpose of the %26?

If someone can kindly explain this to me, it would be greatly appreciated.

Your code so far

function rot13(str) {
  var rotCharArray = [];
  var regEx = /[A-Z]/;
  str = str.split("");
  // spliting the string to make it editable
  for (var x in str) {
    // looping though all characters
    if (regEx.test(str[x])) {
      // checking that is is an upper case letter
      rotCharArray.push(((str[x].charCodeAt() - 65 + 13) % 26) + 65);
     // litterly no idea how this calculation works, but I just know it does, maybe that is good enough?
    } else {
      rotCharArray.push(str[x].charCodeAt());
      // push non-character back unchanges
    }
  }
  str = String.fromCharCode.apply(String, rotCharArray);
  return str;
  // 
}
 
console.log(rot13("SERR PBQR PNZC"));

function rot13(str) {
var rotCharArray = [];
var regEx = /[A-Z]/;
str = str.split("");
for (var x in str) {
  if (regEx.test(str[x])) {
    // A more general approach
    // possible because of modular arithmetic
    // and cyclic nature of rot13 transform
    rotCharArray.push(((str[x].charCodeAt() - 65 + 13) % 26) + 65);
  } else {
    rotCharArray.push(str[x].charCodeAt());
  }
}
str = String.fromCharCode.apply(String, rotCharArray);
return str;
}

// Change the inputs below to test
rot13("LBH QVQ VG!");

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36.

Challenge: Caesars Cipher

Link to the challenge:

That’s one way to do it, but you can also solve this problem without knowing what the character code for “A” is. The important thing is that you don’t want to just subtract 13. The shift cypher works as if the alphabet is a circle.