Solution Explanation please?: Check for Palindromes

Tell us what’s happening:
I saw this intermediate code solution on: freeCodeCamp Algorithm Challenge Guide: Check for Palindromes

function palindrome(str) {

  str = str.toLowerCase().replace(/[\W_]/g, '');
  for(var i = 0, len = str.length - 1; i < len/2; i++) {
    if(str[i] !== str[len-i]) {
      return false;
    }
  }
  return true;
}
palindrome("1 eye for of 1 eye.");
  • Question 1:
    Isn’t the condition expression in the For Loops, where i < len/2, skip the center-most letters during some test? for example, “almostomla”: str.length=10, ends up with i<4.5. therefore it never tests i=5 and i=6, and it would return true when the correct answer is false. Can anybody explain to me why does this solution still work? maybe it connects with my second question, but I just couldn’t make sense of it logically.

  • Question 2:
    When I tried to rewrite my own code after looking through the solution, I set return true within the if statement ( and yes I changed the if statement itself too ), and the test “1 eye for of 1 eye.” failed and gives me “True”. So if the only change I’ve made is to switch false/true placement, why should it matter? I realized there are something logical I’m missing, so can anybody please explain this to me?

Your code so far

function palindrome(str) {

  str = str.toLowerCase().replace(/[\W_]/g, '');
  for(var i = 0, len = str.length - 1; i < len/2; i++) {
    if(str[i] === str[len-i]) {
      return true;
    }
  }
  return false;
}
palindrome("1 eye for of 1 eye.");

Thanks for reading through my nonsense…:frowning: any help is appreciated guys!
Cheers

5 Likes