I passed this checkpoint and was able to get my code to work. My question is why is slice necessary in my code?
Here is my original code. It does not work because although I’ve assigned str to the forComp variable before running reverse on forComp, when I consoled str and forComp in testing they both appear to have been reversed. As a result my if condition always returned true.
function palindrome(str) {
// Good luck!
str = str.replace(/[^A-Z0-9]/ig, '');
str = str.toLowerCase();
str = str.split('');
var forComp = str;
forComp = forComp.reverse();
str = str.join('');
forComp = forComp.join('');
if (forComp == str) {
return true;
} else {
return false;
}
}
palindrome("eye");
Here is my code that works. Why is it that reverse affects str even though I’m running it on the forComp variable? Why does slice make the difference here?
function palindrome(str) {
// Good luck!
str = str.replace(/[^A-Z0-9]/ig, '');
str = str.toLowerCase();
str = str.split('');
var forComp = str.slice();
forComp = forComp.reverse();
str = str.join('');
forComp = forComp.join('');
if (forComp == str) {
return true;
} else {
return false;
}
}
palindrome("eye");
Thank you!