Check if a number is a palindrome in JavaScript
Beginner · 3 min read
A palindrome reads the same forwards and backwards. Words like "level" are palindromes, and so are numbers like 121 and 1221. 123 is not, because backwards it is 321.
In this tutorial you will write a palindrome check for numbers in two ways: one that turns the number into a string, and one that uses only arithmetic. Then you will use it to search for the largest palindrome you can make by multiplying two three-digit numbers, a well-known puzzle. You need to know loops, arrays and how to reverse a number's digits.
Reversing a string
A string can't be reversed directly, but an array can. The spread syntax [...s] turns a string into an array of its characters. Then .reverse() flips the array and .join('') glues it back into a string.
const s = 'level';
console.log([...s]); // [ 'l', 'e', 'v', 'e', 'l' ]
console.log([...'abc'].reverse().join('')); // cba
If the reversed string equals the original, it is a palindrome.
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
44 Palindromic numbers
easyDecide whether a number reads the same backwards. Do it by string and by arithmetic, then find the largest palindrome that is the product of two three-digit numbers.
Stuck? Three hints, smallest first
- 1. The string version splits, reverses and compares. The arithmetic version rebuilds the number in reverse and compares.
- 2. A trailing zero disqualifies a number: 10 reversed is 1.
- 3. For the product search, start both loops at 100 and let the second start where the first is, so no pair is tried twice.
Step 1: the string version
const isPalindrome = (n) => {
const s = String(n);
return s === [...s].reverse().join('');
};
console.log([121, 123, 1221].map(isPalindrome)); // [ true, false, true ]
console.log(isPalindrome(7)); // true
console.log(isPalindrome(10)); // false
Every single digit is a palindrome. 10 is not, because backwards it reads "01". As a number that is just 1, so a number ending in 0 can never be a palindrome (except 0 itself).
Step 2: what about negative numbers?
console.log(isPalindrome(-121)); // false
console.log([...'-121'].reverse().join('')); // 121-
The answer is false, which is what most people want. But look at why: the string '-121' is compared with '121-'. The minus sign moved to the end. The function got the right answer without ever deciding anything about negatives. Keep that in mind for the next step.
Step 3: the arithmetic version
This one rebuilds the number backwards, digit by digit, and compares it with the original. You take the last digit with % 10 and drop it with Math.floor(n / 10).
function isPalindromeByMaths(n) {
if (n < 0) return false;
let rest = n;
let reversed = 0;
while (rest > 0) {
reversed = reversed * 10 + (rest % 10);
rest = Math.floor(rest / 10);
}
return reversed === n;
}
console.log([121, 123, 1221].map(isPalindromeByMaths)); // [ true, false, true ]
console.log(isPalindromeByMaths(-121)); // false
Here negatives are rejected on purpose, on the first line. If you ever decide that -121 should count, this version has one obvious line to change. The string version doesn't.
This version also avoids strings, which matters for very large numbers: String(1e21) is '1e+21', which isn't the number's digits at all.
Step 4: check that they agree
const agree = Array.from({ length: 1000 }, (_, i) => i)
.every((n) => isPalindrome(n) === isPalindromeByMaths(n));
console.log(agree); // true
const below1000 = [];
for (let n = 0; n < 1000; n++) if (isPalindrome(n)) below1000.push(n);
console.log(below1000.length); // 109
Array.from({ length: 1000 }, (_, i) => i) makes the list 0 to 999. every returns true only if the test passes for all of them. There are 109 palindromes below 1000: 10 single digits, 9 with two digits, and 90 with three.
Step 5: the largest palindrome product
Now the puzzle. Try every pair of numbers between low and high, multiply them, and keep the biggest product that is a palindrome.
function largestProductPalindrome(low, high) {
let best = 0;
let pair = null;
for (let a = low; a <= high; a++) {
for (let b = a; b <= high; b++) {
const p = a * b;
if (p > best && isPalindrome(p)) {
best = p;
pair = [a, b];
}
}
}
return { best, pair };
}
console.log(largestProductPalindrome(10, 99)); // { best: 9009, pair: [ 91, 99 ] }
console.log(largestProductPalindrome(100, 999)); // { best: 906609, pair: [ 913, 993 ] }
The inner loop starts at b = a, not at low. 91 times 99 is the same as 99 times 91, so this skips every pair you have already tried. The check p > best comes before isPalindrome(p), so the cheaper comparison runs first.
Step 6: palindromes in another base
isPalindrome only compares characters, so it works on any string, including a number written in binary:
console.log((585).toString(2)); // 1001001001
console.log(isPalindrome((585).toString(2))); // true
585 is a palindrome in base 10 and in base 2.
The full solution
The answer panel has both checks and the product search, then prints the small cases, 10, -121, the two-digit and three-digit results, and 585 in binary. Press Run to see the output.
const isPalindrome = (n) => {
const s = String(n);
return s === [...s].reverse().join('');
};
// No strings: rebuild the number backwards and compare.
function isPalindromeByMaths(n) {
if (n < 0) return false;
let rest = n;
let reversed = 0;
while (rest > 0) {
reversed = reversed * 10 + (rest % 10);
rest = Math.floor(rest / 10);
}
return reversed === n;
}
function largestProductPalindrome(low, high) {
let best = 0;
let pair = null;
for (let a = low; a <= high; a++) {
for (let b = a; b <= high; b++) {
const p = a * b;
if (p > best && isPalindrome(p)) {
best = p;
pair = [a, b];
}
}
}
return { best, pair };
}
const twoDigit = largestProductPalindrome(10, 99);
const threeDigit = largestProductPalindrome(100, 999);
const below1000 = [];
for (let n = 0; n < 1000; n++) if (isPalindrome(n)) below1000.push(n);
console.log('121, 123, 1221 :', [121, 123, 1221].map(isPalindrome));
console.log('10 :', isPalindrome(10), '<- 10 reversed is 1');
console.log('-121 :', isPalindrome(-121), isPalindromeByMaths(-121));
console.log('two-digit best :', twoDigit);
console.log('three-digit :', threeDigit);
console.log('585 in binary :', (585).toString(2));
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('121 and 1221 read the same both ways, 123 does not', [121, 1221, 123].map(isPalindrome), [true, true, false]);
test('single digits and 0 are palindromes, 10 is not', [0, 7, 10].map(isPalindrome), [true, true, false]);
test('both versions reject negatives, for different reasons', [isPalindrome(-121), isPalindromeByMaths(-121)], [false, false]);
test('and they agree on every number below 1000', Array.from({ length: 1000 }, (_, i) => i).every((n) => isPalindrome(n) === isPalindromeByMaths(n)), true);
test('there are nine two-digit palindromes', below1000.filter((n) => n >= 10 && n < 100), [11, 22, 33, 44, 55, 66, 77, 88, 99]);
test('and 109 palindromes below 1000 in total', below1000.length, 109);
test('the largest palindrome from two 2-digit numbers is 91 x 99', [twoDigit.best, twoDigit.pair], [9009, [91, 99]]);
test('and from two 3-digit numbers, 913 x 993', [threeDigit.best, threeDigit.pair], [906609, [913, 993]]);
test('585 is a palindrome in base 10 and in base 2', [isPalindrome(585), isPalindrome((585).toString(2))], [true, true]);
The string version is shorter and the arithmetic version is the one to reach for when the digits might not survive String — past 1e21 that switches to exponential form, as exercise 42 showed, and '1e+21' is not a palindrome for reasons that have nothing to do with the number.
Both versions reject negatives, which looks like agreement and is not. The arithmetic one refuses explicitly; the string one compares '-121' with '121-' and gets the right answer by accident. That distinction matters the moment you decide -121 should count, because only one of the two has a place to put the change. Note also that isPalindrome works unchanged on the binary string, since it only ever compares characters.
Common mistakes
- Forgetting that
reverseis for arrays. Strings don't have areversemethod. Spread into an array first. - Relying on the string version for negatives. It returns
falseonly because the minus sign moves. Decide on negatives explicitly, as the arithmetic version does. - Starting the inner loop at
low. It works, but it tries every pair twice. Start ata.
Try it yourself
- List every two-digit palindrome. You should get nine.
- Find the largest palindrome that is the product of two numbers from 10 to 30.
- Find all numbers below 1000 that are palindromes in both base 10 and base 2.