Search code examples
javascriptfunctionpalindrome

JavaScript Palindrome


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!


Solution

  • 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