2

I'm writing a code in order to know if a word is a Palindrome. I think my code is correct but I get undefined on "newStr". Like the console tells me that : console.log(newStr) // undefinedracerar I don't understand why and I bet that why I get "false" for my return because I think the code is correct. Here my code below. Thanks

function palindrome(str) {
  //   console.log(str);
  str = str.split(" ").join("").toLowerCase();
  //   console.log(str);
  //   console.log(str.length);

  let newStr = "";
  for (let i = str.length; i >= 0; i--) {
    newStr = newStr + str[i];
  }
  console.log(newStr);

  if (str === newStr) {
    return true;
  } else return false;
}

console.log(palindrome("rarecar"));
tripathiakshit
  • 624
  • 5
  • 17
  • What happens if you ask for `a[10]` of an array that is 10 long (keep in mind that arrays that are 10 long will have elements from `a[0]` to `a[9]`)? – mjwills Jul 31 '20 at 00:17

2 Answers2

3

As others have pointed out, your code length was off-by-one, and can be fixed by changing the loop invariant's initial value.

But I want to point out that there's a much simpler way to solve this. You can simply reverse the array you get when you split the string. This avoids many such problems from happening in the first place, and result in simpler code.

function palindrome(str) {
  return str === str.split("").reverse().join("");
}

console.log(palindrome("racecar")); // returns true
console.log(palindrome("rarecar")); // returns false
tripathiakshit
  • 624
  • 5
  • 17
2

let i = str.length should be let i = str.length - 1

This is str[str.length] is not an index of str, it is one higher than the last index of str, since indexes start at 0.

Cory Harper
  • 1,023
  • 6
  • 14