Why do I get undefined? (JS)

Viewed 53

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"));

2 Answers

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

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.

Related