Check for Palindromes if loop

Tell us what’s happening:
why doesn’t this work when I used == and true on the if statement while it worked when I used != and false in my if statement. Doesn’t both mean same?

Your code so far

function palindrome(str) {
  var front = 0;
  var back = str.length - 1;

  //back and front pointers won't always meet in the middle, so use (back > front)
  while (back > front) {
    //increments front pointer if current character doesn't meet criteria
    while ( str[front].match(/[\W_]/) ) {
      front++;
      continue;
    }
    //decrements back pointer if current character doesn't meet criteria
    while ( str[back].match(/[\W_]/) ) {
      back--;
      continue;
    }
    //finally does the comparison on the current character
    if ( str[front].toLowerCase() == str[back].toLowerCase() ) 
      return true ;
    front++;
    back--;
  }
  
  //if the whole string has been compared without returning false, it's a palindrome!
  return false;

}

palindrome("almostomla");

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36.

Link to the challenge:
https://www.freecodecamp.org/challenges/check-for-palindromes

If you have:

if ( str[front].toLowerCase() == str[back].toLowerCase() ) 
      return true ;

It is going to return true immediately after confirming that the first and last character match. It never gets to check anything else. Remember that return exits the function. You want it to keep checking and only return (there at least) if the characters don’t match.

Also, your last return should be true.

2 Likes

Oh yeah, got it. Thank You for the clarification…