1

This function cleans up a string (removes all non-alphanumeric characters including underscores) then splits each letter into an array so that it can be reversed, then checked against the original.

At console.log(cleanStr) , it is returning the reversed array but I do not know why.

function checkIfPalindrome(str) {
  var cleanStr = str.toLowerCase().replace(replace, "" ).split("");
  var reversedStr = cleanStr.reverse();

  console.log(cleanStr); // why is this returning reverseStr, the reversed array? 

  if (cleanStr == reversedStr){
     return true
   }
  return false
}

checkIfPalindrome("five|\_/|four"); 

2 Answers 2

3

The reverse() method reverses an array in place - it mutates the array it's called on. Try creating a new array instead:

const cleanStr = str.toLowerCase().replace(replace, "" ).split("");
const reversedStr = [...cleanStr].reverse();
Sign up to request clarification or add additional context in comments.

Comments

1

At console.log(cleanStr) , it is returning the reversed array but I do not know why.

Because reverse reverses it in place.

Separately, you have a problem here:

if (cleanStr == reversedStr){

If they were different arrays, that would always be false, even if they had the same contents.

If you want to make a copy of the array and then reverse it, throw a .slice() in there:

var reversedStr = cleanStr.slice().reverse();
// -----------------------^

...and then compare after turning them back into strings:

if (cleanStr.join("") === reversedStr.join(""))

(I'd probably change those variable names, too, as they don't refer to strings.)

And finally, any time you find yourself writing:

if (x == b) {
    return true;
}
return false;

back up and write

return x == b;

instead. :-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.