Sidratul Muntaha Ibne Rahman Sidratul Muntaha Ibne Rahman - 4 years ago 389
Javascript Question

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!

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download