Emmanuel Akinfulubi

JavaScriptRecursion

Palindrome check using recursion in JavaScript

Beginner · 3 min read

A palindrome is a word that reads the same forwards and backwards: "madam", "level", "racecar". Checking for one is a classic beginner exercise, and doing it with recursion is especially neat, because a palindrome is built from smaller palindromes. Strip the first and last letters off "racecar" and you get "aceca", which is also a palindrome.

In this tutorial you will write isPalindrome(text) recursively, test it on the four words from the task, and then extend it to whole sentences like "A man, a plan, a canal - Panama". You need to know strings, indexes and functions. Recursion is explained below.

The idea in plain words

To check a word, compare its first and last letters.

  • If they are different, it is not a palindrome. Stop.
  • If they are the same, throw them away and check what is left in the middle.

Keep going until there is nothing left to compare. A word of one letter, or no letters at all, always reads the same both ways.

A function that solves a problem by calling itself on a smaller piece is recursive. The point where it stops, here a string of 0 or 1 characters, is the base case.

Two string tools you need

text[0] is the first character and text[text.length - 1] is the last. slice(1, -1) cuts both ends off at once, because -1 means "one from the end":

JavaScript

const word = 'madam';
console.log(word[0]);               // 'm'
console.log(word[word.length - 1]); // 'm'
console.log(word.slice(1, -1));     // 'ada'

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

10 Palindrome check by recursion

easy

Decide whether a word reads the same backwards, recursively. The test data: "madam" true, "abdb" false, "ab" false, "a" true.

Stuck? Three hints, smallest first
  1. 1. Compare the first and last characters, then recurse on what is between them.
  2. 2. A string of 0 or 1 characters is a palindrome, so that is your base case.
  3. 3. For real sentences you must strip punctuation and case first, which is a separate step.

Step 1: the base case

Short strings are palindromes, so answer them straight away:

Step 1

function isPalindrome(text) {
  if (text.length <= 1) return true;
  return 'not done yet';
}
console.log(isPalindrome('a')); // true
console.log(isPalindrome(''));  // true

The empty string counts as a palindrome by convention. It also matters for even-length words, as you'll see in Step 3.

Step 2: compare the ends

If the first and last characters differ, the answer is false with no more work:

Step 2

function isPalindrome(text) {
  if (text.length <= 1) return true;
  if (text[0] !== text[text.length - 1]) return false;
  return 'not done yet';
}
console.log(isPalindrome('ab'));   // false
console.log(isPalindrome('abdb')); // false

Step 3: recurse on the middle

If the ends match, the answer depends only on the middle. That is the same question on a shorter string:

Step 3

function isPalindrome(text) {
  if (text.length <= 1) return true;
  if (text[0] !== text[text.length - 1]) return false;
  return isPalindrome(text.slice(1, -1));
}
console.log(isPalindrome('madam')); // true
console.log(isPalindrome('abdb'));  // false
console.log(isPalindrome('ab'));    // false
console.log(isPalindrome('a'));     // true
console.log(isPalindrome('abba'));  // true

Here is what happens for the two longer test words:

Worked example

'madam'  m = m, check 'ada'
'ada'    a = a, check 'd'
'd'      one letter: true

'abdb'   a ≠ b: false

An even-length word like 'abba' goes 'abba', then 'bb', then ''. That's why the base case needs <= 1 and not === 1: the empty string is where even words end.

Step 4: capital letters count

The plain version compares characters exactly, so an uppercase M and a lowercase m are different:

JavaScript

function isPalindrome(text) {
  if (text.length <= 1) return true;
  if (text[0] !== text[text.length - 1]) return false;
  return isPalindrome(text.slice(1, -1));
}
console.log(isPalindrome('Madam')); // false

That is correct for a strict check. For real sentences, you usually want to ignore case, spaces and punctuation. Do that as a separate step before checking.

Step 5: clean, then check

toLowerCase() makes every letter small. replace(/[^a-z0-9]/g, '') uses a regular expression, a pattern for matching text: [^a-z0-9] means "any character that isn't a lowercase letter or a digit", and the g flag means "everywhere". Each match is replaced with nothing:

Step 5

function isPalindrome(text) {
  if (text.length <= 1) return true;
  if (text[0] !== text[text.length - 1]) return false;
  return isPalindrome(text.slice(1, -1));
}
const clean = (text) => text.toLowerCase().replace(/[^a-z0-9]/g, '');
const isPalindromeSentence = (text) => isPalindrome(clean(text));
console.log(clean('A man, a plan, a canal - Panama'));                // 'amanaplanacanalpanama'
console.log(isPalindromeSentence('A man, a plan, a canal - Panama')); // true
console.log(isPalindromeSentence('Lagos to Abuja'));                  // false

Keeping cleaning and checking apart means the recursive function stays two lines, and you decide on purpose what to ignore.

The full solution

The panel has the recursive check, the sentence version, and a second method that reverses the string, used to cross-check every answer. Press Run to see the output.

The answer

function isPalindrome(text) {
  if (text.length <= 1) return true;                       // '' and 'a'
  if (text[0] !== text[text.length - 1]) return false;
  return isPalindrome(text.slice(1, -1));                  // drop both ends
}

// The version that copes with a real sentence: normalise, then check.
const clean = (text) => text.toLowerCase().replace(/[^a-z0-9]/g, '');
const isPalindromeSentence = (text) => isPalindrome(clean(text));

// A completely different method, as a cross-check.
const byReversal = (text) => text === [...text].reverse().join('');

for (const w of ['madam', 'abdb', 'ab', 'a', '']) {
  console.log(JSON.stringify(w).padEnd(8), '->', isPalindrome(w));
}
console.log('A man, a plan, a canal - Panama ->', isPalindromeSentence('A man, a plan, a canal - Panama'));
console.log('cleaned:', clean('A man, a plan, a canal - Panama'));

Output


      
11 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 11 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

11 checks

test("'madam' is a palindrome", isPalindrome('madam'), true);
test("'abdb' is not", isPalindrome('abdb'), false);
test("'ab' is not", isPalindrome('ab'), false);
test("'a' is", isPalindrome('a'), true);
test("'' is, by convention", isPalindrome(''), true);
test('an even-length one works too', isPalindrome('abba'), true);
test('the reversal method agrees on all of them', ['madam', 'abdb', 'ab', 'a', '', 'abba', 'racecar'].every((w) => isPalindrome(w) === byReversal(w)), true);
test('case matters to the plain version', isPalindrome('Madam'), false);
test('the sentence version ignores case and punctuation', isPalindromeSentence('A man, a plan, a canal - Panama'), true);
test('11/11/11 11:11 also passes once cleaned', isPalindromeSentence('11/11/11 11:11'), true);
test('and a real sentence still fails', isPalindromeSentence('Lagos to Abuja'), false);

slice(1, -1) removes both ends in one step, which is what makes the recursion two lines. The case assertion is the part people skip: 'Madam' is not a palindrome by strict character comparison, so normalising is a deliberate decision rather than an accident. Note also that [...text] is used instead of text.split('') in the cross-check, because spreading iterates by code point and keeps characters outside the basic range in one piece.

Common mistakes

  • Using === 1 as the base case. Even-length words shrink to the empty string, which then never stops. Use <= 1.
  • Forgetting the minus in slice(1, -1). slice(1, 1) returns an empty string, so every word with matching ends would look like a palindrome.
  • Cleaning inside the recursion. Cleaning the whole string again on every call repeats the same work. Clean once, then check.

Try it yourself

  1. Add a counter and find how many calls isPalindrome('racecar') makes.
  2. Rewrite the check without slice, by passing two positions, left and right, that move toward the middle.
  3. Write isPalindromeNumber(n) that checks a number like 12321. (Hint: String(n).)

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.