Search code examples
javascriptrecursionpalindrome

Recursive palindrome check with JavaScript


I am trying to find out whether a string is a palindrome by recursion using javascript. But I can't figure out what I am missing in the code.

var firstCharacter = function(str) {
    return str.slice(0, 1);
};

var lastCharacter = function(str) {
    return str.slice(-1);
};

var middleCharacters = function(str) {
    return str.slice(1, -1);
};

var isPalindrome = function(str) {
    if(str.length < 2) {
        return true;
    } else {
        if(firstCharacter(str) == lastCharacter(str)) {
            isPalindrome(middleCharacters(str));
        } else return false;
    }
};

var checkPalindrome = function(str) {
    console.log("Is this word a palindrome? " + str);
    console.log(isPalindrome(str));
};


checkPalindrome("a");
//Program.assertEqual(isPalindrome("a"), true);
checkPalindrome("matom");
//Program.assertEqual(isPalindrome("motor"), false);
checkPalindrome("rotor");
//Program.assertEqual(isPalindrome("rotor"), true);

For sure something is wrong with the recursive call. I would love to have your help. Thanks. I am attaching the output of my code.

enter image description here


Solution

  • You defined isPalindrome() to return a value, so if you call it yourself, recursively or otherwise, you need to deal with that return value. Also, your if ... else logic is too complicated, simplify:

    var isPalindrome = function(str) {
        if (str.length < 2) {
            return true;
        }
    
        if (firstCharacter(str) == lastCharacter(str)) {
            return isPalindrome(middleCharacters(str));
        }
    
        return false;
    };