Check for Palindromes, i was trying this intermediate solution, but in for loop it is ( i < len-i ) works instead of ( i > len-i )which i think it should be a stop condition, right? can anyone figure out why?

Check for Palindromes, i was trying this intermediate solution, but in for loop it is ( i < len-i ) works instead of ( i > len-i )which i think it should be a stop condition, right? can anyone figure out why?
0

#1

Tell us what’s happening:

Your code so far

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



palindrome("not a palindrome");

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36.

Link to the challenge:


#2

Actually, your (i < len - i) works, but all you really needed was (i < len).

If you use (i > len - i), then nothing inside the for loop would run, because when i is initialized to 0 and len is assigned str.length -1, the for loop condition would be evaluating 0 < len - 0, so no matter what the value of len is (0, 1, 2, 3, 4, 5…100), the for loop condition would evaluate to false, so the for loop code block would never execute.


#3

yea, i figure out eventually, i took the wrong note when i study for loop, and it mistake me all the time. i thought it is a stop condition when it is true, which actually it is a stop condition when it is false. a false note really let me ask stupid question…lol