JavaScript Algorithms and Data Structures Projects - Palindrome Checker

Hi! I´m trying to do the Palindrome Challenge. I don´t understand why the result string always has “undefined” at the beggining.

Your code so far

function palindrome(str) {
  let regex = /\w+/gi;
  let noSpaces = str.match(regex); 
  let newStr = []; 
  let result = [];
  for (let word in noSpaces){
    newStr += noSpaces[word];
  }
  for (let i = newStr.length; i >= 0; i--){
    result += newStr[i];
  } 
  console.log(result) /* **this returns "undefinedeye"** */;
  if (result === noSpaces){
    return true
  } else {
    return false
  } 
} 

console.log(palindrome("eye"));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36

Challenge: JavaScript Algorithms and Data Structures Projects - Palindrome Checker

Link to the challenge:

JavaScript uses zero-indexed strings.

FYI, this will produce an array containing the first sequence of word characters, so if there are spaces between characters, this will only capture the first sequence and none of the rest.

Yes, but I thought of doing let i = newStr.length + 1; but it didnt´t work? Maybe i didn´t do it correctly

That is going the wrong direction. Strings use zero-based indexing.

const str = 'abc';
console.log(str.length); // displays 3
console.log(str[0]); // displays a
console.log(str[1]); // displays b
console.log(str[2]); // displays c
console.log(str[3]); // displays undefined because there is no index beyond 2
1 Like

Ohhhh, you´re rigth! Thank you!