I am currently trying to understand what is achieved when we divide a string's length by two. I understand how the loop in the if statement works by comparing each character with the initial string, but I can't wrap my head around this part and I can't find a good explanation of it anywhere.
If we divide a string's length in two what is it doing? I.e. with the word 'Madam' - If 'i' is more than 5/2 [2.5], the loop stops incrementing? Once it has checked [m][0], [a][1], [d][2] - it stops at [a][3] because it is no longer necessary to check as we know it to already be true/false as it mirrors the other half of the word?
function aPalindrome(str) {
for (let i = 0; i < str.length / 2; i++) {
if (str[i] != str[str.length - 1 - i]) {
return false;
}
return true;
}
}
Palindrome is a word, phrase, or sequence that reads the same backwards as forwards. Therefore we divide it half to check with the other half. we don't need to check the whole thing.
With Example: madam, we are already checking str[0] == str[4], therefore we don't need to check str[4] == str[0]