Caesar cipher in JavaScript
Intermediate · 4 min read
The Caesar cipher is one of the oldest secret codes. It's named after Julius Caesar, who is said to have used it in his letters. You shift every letter along the alphabet by a fixed number of places: with a shift of 3, A becomes D, B becomes E, and at the end, X, Y and Z wrap round to A, B and C.
It isn't real security, but it's a perfect exercise in working with character codes and wrapping numbers round. In this tutorial you will write shift(text, by), which shifts letters, keeps upper and lower case, leaves everything else alone, and undoes itself with a negative shift. You need to know loops and strings. Character codes and the wrap-around maths are explained below.
Letters are numbers underneath
Every character has a number, called its character code. Capital A is 65, B is 66, all the way to Z at 90. Lowercase a is 97 to z at 122. The letters of each case sit next to each other, in order.
console.log('A'.charCodeAt(0)); // 65
console.log('a'.charCodeAt(0)); // 97
console.log(String.fromCharCode(68)); // D
charCodeAt(0) gives the code of the first character. String.fromCharCode turns a code back into a character.
Position in the alphabet
To shift a letter, it's easier to work with its position, 0 to 25, than its code. Subtract the code of A (or a for lowercase), shift, and add it back:
const code = 'Y'.charCodeAt(0); // 89
const position = code - 65; // 24
console.log(position + 3); // 27: past the end of the alphabet
console.log((position + 3) % 26); // 1, which is B
% 26 is the remainder after dividing by 26. It wraps 26 back to 0, 27 to 1, and so on, the same way a clock wraps 13 o'clock round to 1.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
140 A letter shift that wraps round the alphabet
fairShift every letter in a message along the alphabet by a number of places, wrapping z round to a. Leave punctuation, spaces and digits alone, keep upper and lower case as they were, and make a negative shift undo a positive one.
Stuck? Three hints, smallest first
- 1. Work with character codes:
charCodeAtout,String.fromCharCodeback. - 2. Subtract the code of
Aorafirst so the letter is 0 to 25, then add it back. - 3.
%can return a negative, so((x % 26) + 26) % 26is what actually wraps.
Step 1: shift capital letters
const A = 'A'.charCodeAt(0);
function shiftUpper(text, by) {
let out = '';
for (const ch of text) {
const code = ch.charCodeAt(0);
const moved = (code - A + by) % 26;
out += String.fromCharCode(A + moved);
}
return out;
}
console.log(shiftUpper('LAGOS', 3)); // ODJRV
console.log(shiftUpper('XYZ', 3)); // ABC
for (const ch of text) gives us one character at a time. Each one is turned into a position, shifted, wrapped with % 26, and turned back into a letter.
Step 2: both cases, and leave the rest alone
Lowercase letters need base 97 instead of 65. Anything that isn't a letter, like spaces, digits and punctuation, should pass through unchanged. A base variable decides which case we're in, or null if it isn't a letter:
const A = 'A'.charCodeAt(0);
const a = 'a'.charCodeAt(0);
function shift(text, by) {
let out = '';
for (const ch of text) {
const code = ch.charCodeAt(0);
const base = code >= A && code <= A + 25 ? A : code >= a && code <= a + 25 ? a : null;
if (base === null) {
out += ch; // not a letter, left alone
continue;
}
out += String.fromCharCode(base + ((code - base + by) % 26));
}
return out;
}
console.log(shift('Meet me at Ojuelegba, 6pm!', 3)); // Phhw ph dw Rmxhohjed, 6sp!
console.log(shift('zZ', 1)); // aA
Using one base means the same arithmetic works for both cases, so we don't need two copies of the logic. continue jumps to the next character.
Step 3: shifting back goes wrong
To decode, shift by the negative amount. Try it:
const A = 'A'.charCodeAt(0);
const a = 'a'.charCodeAt(0);
function shift(text, by) {
let out = '';
for (const ch of text) {
const code = ch.charCodeAt(0);
const base = code >= A && code <= A + 25 ? A : code >= a && code <= a + 25 ? a : null;
if (base === null) {
out += ch;
continue;
}
out += String.fromCharCode(base + ((code - base + by) % 26));
}
return out;
}
console.log(shift('aA', -1)); // `@
console.log(-1 % 26); // -1
Instead of zZ we get a backtick and an @ sign. In JavaScript, % keeps the sign of the number on the left, so -1 % 26 is -1, not 25. Adding -1 to the code of a lands on the character just before it.
Step 4: the double remainder
The fix is to add 26 and take the remainder again:
console.log(((-1 % 26) + 26) % 26); // 25
console.log(((27 % 26) + 26) % 26); // 1
console.log(((-27 % 26) + 26) % 26); // 25
The first % brings the number into the range -25 to 25. Adding 26 makes it positive. The second % wraps anything that is now 26 or more back down. It works for any shift, positive or negative, big or small.
Put that into shift:
const A = 'A'.charCodeAt(0);
const a = 'a'.charCodeAt(0);
function shift(text, by) {
let out = '';
for (const ch of text) {
const code = ch.charCodeAt(0);
const base = code >= A && code <= A + 25 ? A : code >= a && code <= a + 25 ? a : null;
if (base === null) {
out += ch;
continue;
}
const moved = (((code - base + by) % 26) + 26) % 26;
out += String.fromCharCode(base + moved);
}
return out;
}
const message = 'Meet me at Ojuelegba, 6pm!';
console.log(shift('aA', -1)); // zZ
console.log(shift(shift(message, 3), -3)); // Meet me at Ojuelegba, 6pm!
console.log(shift(message, 29) === shift(message, 3)); // true
console.log(shift(shift(message, 13), 13) === message); // true
Shifting by 29 is the same as shifting by 3, because 26 is a full trip round the alphabet. A shift of 13 is called ROT13: doing it twice gets you back to the start, because 13 + 13 = 26.
The same "double remainder" trick is useful anywhere a number wraps round going backwards: clock faces, image carousels, and days of the week.
The full solution
The answer panel has shift with the double remainder, and rot13. It encodes a message with a shift of 3 and decodes it again. Press Run to see the output. Remember this is a puzzle, not security: there are only 25 possible shifts, so anyone can try them all.
const A = 'A'.charCodeAt(0); // 65
const a = 'a'.charCodeAt(0); // 97
function shift(text, by) {
let out = '';
for (const ch of text) {
const code = ch.charCodeAt(0);
const base = code >= A && code <= A + 25 ? A : code >= a && code <= a + 25 ? a : null;
if (base === null) {
out += ch; // not a letter, left alone
continue;
}
const moved = (((code - base + by) % 26) + 26) % 26; // the double modulo is the wrap
out += String.fromCharCode(base + moved);
}
return out;
}
const rot13 = (text) => shift(text, 13);
const message = 'Meet me at Ojuelegba, 6pm!';
console.log(message);
console.log('shift 3 ->', shift(message, 3));
console.log('back ->', shift(shift(message, 3), -3));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the classic three-place shift', shift('Lagos', 3), 'Odjrv');
test('and shifting back returns the message', shift(shift(message, 3), -3), message);
test('case survives, and anything that is not a letter is untouched', shift(message, 3), 'Phhw ph dw Rmxhohjed, 6sp!');
test('z wraps to a and Z to A', shift('zZ', 1), 'aA');
test('a negative shift wraps the other way', shift('aA', -1), 'zZ');
test('a whole alphabet of shift changes nothing', shift(message, 26), message);
test('so shifting by 29 is shifting by 3', shift(message, 29), shift(message, 3));
test('rot13 is its own inverse', rot13(rot13(message)), message);
test('and without the double modulo the wrap would break', [-1 % 26, ((-1 % 26) + 26) % 26], [-1, 25]);
The base variable is the idea: subtract the code of the case's first letter to get a position 0 to 25, do the arithmetic there, add the base back. That is what keeps upper and lower case separate without two copies of the logic, and it generalises to any contiguous alphabet.
((x % 26) + 26) % 26 looks like superstition until you check the last assertion. JavaScript's % is a remainder, not a mathematician's modulo, so it keeps the sign of the left operand: -1 % 26 is -1, which added to the base of 'a' gives the backtick character. Every wrapping index — clock faces, circular buffers, carousels stepping backwards — needs the same guard.
Nothing here is encryption. A shift cipher has 25 possible keys, so it is broken by trying all of them, and English letter frequencies give it away instantly. It is a puzzle and a good exercise in character arithmetic. Anything that actually needs to be secret goes through crypto.subtle, not through this.
Common mistakes
- Using
% 26alone. Negative shifts produce characters that aren't letters. Use((x % 26) + 26) % 26. - Shifting every character. Spaces, digits and punctuation must pass through unchanged.
- Treating upper and lower case the same. Each case has its own base code, 65 or 97.
Try it yourself
- Write
crack(text)that prints the text decoded with all 25 shifts, so you can spot the readable one. - Make digits shift too, wrapping within 0 to 9.
- Write a Vigenère cipher: use a keyword like
"KEY", and shift each letter by the matching letter of the keyword (K is 10, E is 4, Y is 24).