Search code examples
javascriptif-statementrecursionpalindrome

Getting False on a recursive function with if conditions trying to solve the "Palindrome" Challenge


So I was doing this popular challenge "palindrome" and I was copying this solution from the "Frontend Masters" Javascript Series and I'm getting a different output. I want to know if there is something that changes or am I missing something. This is my first question on StackOverflow because this is just MindF***k.

What is going on?


'use strict'

function isPalindrome(str) {
  if (str.length <= 1) return true;
  var first = str[0];
  var last = str[str.length - 1];
  if (first === last) {
    console.log(str.substring(1, str.length - 1))
    isPalindrome(str.substring(1, str.length - 1));
  }
  return false;
}

console.log(isPalindrome("abcdcba")) // Return false on my machine

I try this on the RunJS app as well as the VScode terminal and also I run Node on the file.

KEEP RETURNING FALSE !!


Solution

  • I fixed your code...

    'use strict'
    
    function isPalindrome(str) {
      if (str.length <= 1) return true;
      var first = str[0];
      var last = str[str.length - 1];
      if (first === last) {
        console.log(str.substring(1, str.length - 1))
        return isPalindrome(str.substring(1, str.length - 1));
      }else return false;
    }
    
    console.log(isPalindrome("abcdcba")) // 

    I see recursive functions having two different parts:

    1. Going forward when the function starts calling itself and stacking function calls.
    2. in a reverse way going backward when all the stack functions start returning values. In your example this phase is kickoff just after if (str.length <= 1) return true or if first !== last.

    I think you you did it totally right going forward, but there was a minor details in the come back. You need to remember that ones you have your solution you need to return values through all the calls back to the initial one.

    A recursive function is kind of split in two:

    function recursive{
    
      //forward processing
      ..
      resultValue = recursive()
      ..
      // backward processing if needed
      return kindOfResultValue //resultValue or a transformation if needed
    }
    

    Note: Remember to check all conditional branches of your recursive function to return always a value after calling itself