Palindrome Checker - Why is the default return of true not occurring?

The test passes anything that should be false.

However, if an input is supposed to be true i.e. it is a Palindrome, the function does not do this?

I believe .replace(/[\W_]/g,"");
removes anything non-alphanumerical and white spaces. Is this correct?

By default, the function should return true. As stated in the penultimate line of code after both for loops:

return true

It turns false correctly for any input that is not palindrome.

The for loop, if every character at position i equals the character at position j , then the if statement inside will not execute. As a result, the function returns true as default.

However, this is not happening? Could someone please provide a pointer in the correct direction. Thanks


function palindrome(str) {

var lcStr = str.toLowerCase()


var nonANstr = lcStr.replace(/[\W_]/g,"");

for (var i = 0 ; i<=nonANstr.length;i++) {
  for (var j=nonANstr.length ; j>=0 ; j--) {

    if (nonANstr[i]!=nonANstr[j]){
      console.log(nonANstr[i])
      console.log(nonANstr[j])
      return false;
    }
  }
}

return true;
}



palindrome("eYYe_y");

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/palindrome-checker/

I see two problems:

  1. You shouldn’t nest the loops, you only need one loop with 2 counter variables. If you nest the loops, i.e. it will check the first letter against all the letters, one iteration at a time from the back => it is deemed to always return false.
  2. In the second loop the variable j should not start from str.length but from str.length - 1.
1 Like

Legend, thanks. All done :slight_smile:

function palindrome(str) {

var lcStr = str.toLowerCase()


var nonANstr = lcStr.replace(/[\W_\s+]/g,"");

for (var i = 0 , j=nonANstr.length-1 ; i<=nonANstr.length , j>=0 ;i++,j--) {
   {

    if (nonANstr[i]!=nonANstr[j]){
    
      return false;
    }
  }
}

return true;


}

Saw that you solved it, you could also use functional programming instead of looping.

function palindrome(str) {
 	let arr = [...str.replace(/[\s_\W]*/g, '')];
  
  return arr.toString().toLowerCase() === arr.reverse().toString().toLowerCase()
   ? true : false;
}

Thank you for the alternative.

I’m currently revising forEach loops where they have an anonymous function.

For my solution in post number 3, how would you write it as a for each loop?

the forEach loop will just take one element/index at a time. I wouldn’t use that, since you need to compare the reversed value with the regular value of the string. Which .reverse() handles easily :slight_smile: