Creating a Palindrome function

Here is what I have so far:

function palindrome(str) {
const strArray = str
for (let i = 0; i < (strArray.length - 1) - i; i++) {
if (strArray[i + 0] !== strArray[(strArray.length - 1) - i]) {
return false
} else {
return true

My issue is with words like “barkab” or “almostomla” but I can’t see why the function doesn’t return false for these strings. Any palindrome I’ve tested has come back true.

So, when plugging “barkab” into the function, my thinking was:

  • break the string up into an array. this part seems to be working as expected and I don’t think there is an issue here.

  • then perform a for loop to iterate through each index and compare it with the end index minus the number of iterations; so for the first loop it would be comparing strArray[0 + 0] with strArray((strArray.length -1) - 0)

  • when i = 2; 2 < (6 - 1) - 2 //this is true so the loop will go on
    if(strArray[0 +2] is not equal to strArray[(6 - 1) - 2] then return false;
    if (r at index 2) is not equal to (k at index 3) then return false;
    and yet the function returns true.

A nod in the right direction would be very helpful here. I feel like I’m glossing over something pretty simple. Or perhaps this isn’t the best way to perform the loop.

Look at this snippet very closely. What is guaranteed to happen? How many times will the for loop actually iterate based on this?

1 Like

Thanks for the tip! I removed the else statement so now it actually iterates through the string instead of just the first and last index. The “return true” just needed to be set for the function in the case that the if statement was never met. On to the next challenge!

1 Like