-4

I found a solution on how to write palindrome in StackOverFlow. This is the code snippet:

function palindrome(str) {
    var len = str.length;
    for ( var i = 0; i < Math.floor(len/2); i++ ) {
        if (str[i] !== str[len - 1 - i]) {   //Problem in this line
            return false;
        }
    }
    return true;
}

I understand every line except the one I have here. Can anyone please break it down for me? Thanks in advance!

Brandon A.
  • 27
  • 6

2 Answers2

1

The loop steps through the first half of the string, and it checks consecutive character to see if it is not equal (or not the same character) to the next consecutive character on the other end of the string, starting from the end.

|0|1|2|3|4|
|l|e|v|e|l|

len = 5

This gives you:

str[i] !== str[len - 1 - i]

When i = 0, str[i] is l, which is equal to str[5-1-0], which is str[4], which also is l

Bert
  • 2,134
  • 19
  • 19
0

str[i] represents the (i+1)th character in str. If str is a palindrome then this character must be equal to the character that is i positions from the end of the string (by definition).

The last character in a string is at position len - 1 (since len was defined as being the length of the string, and indexes start counting from 0). So you need to subtract i from that to arrive at the position where the character sits that should be the same as str[i]. Hence str[len - 1 - i]

The comparison is made with !==, i.e. not-equal. In that case we know for sure we do not have a palindrome and can exit with false.

trincot
  • 317,000
  • 35
  • 244
  • 286