Check for Palindromes - Why is slice needed in my code?

Check for Palindromes - Why is slice needed in my code?
0

#1

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!


#2
str = str.split('');
var forComp = str;

You can’t copy array like that.
str doesn’t have an array inside it, but a reference to memory location where the array data is located. What you did there is you created another reference, but they both point to the same array, so when you reverse forComp you are reversing str also.

Google “javascript pass by reference”


#3

Ah, thank you very much jenovs. Much appreciated!


#4

oh god yes! I spent hours trying to figure out why one of my challenges was changing the original array I had copied way back when…

as @jenovs mentioned…

Reference I had used to figure out I needed to clone an array: https://davidwalsh.name/javascript-clone-array

I know the new curriculum is well on it’s way but that might be a good tip somewhere in it…