My Code_Check for Palindromes

Tell us what’s happening:
My code works for all the return true criteria but none of the return false criteria.
Also what does /[\W_]/ stand for? (I looked at the hint and everyone posted this in their replace statement. Is this short for all non-alphanumeric characters?


Your code so far

function palindrome(str) { 
  var newstr = str.replace(/[\W_]/g, "");
  var array = newstr.split("");
var newArray = [];
newArray = array.reverse();
if(array == newArray){
     return true;
  return false;


Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36.

Link to the challenge:

You can not directly compare arrays the way you are (array == newArray). Convert the arrays to strings (hint: join) and then you can make a direct comparison.

/[\W_]/ means all non-word character or underscore

1 Like

In javascript objects (thus array as well) are reference to the data.

This means that when assigning a variable to and object, you are assigning “the address” where the data is stored inside the memory.
So if two arrays are pointing to the same address will change the same data:

const a = [1, 2, 3]; // imagine I have this data;
const b = a // now b is pointing to the same "address" of where a is pointing

changing any values of b will change a as well, 
since they are pointing to the same data

b[1] = 'test' // [1, 'test', 3];
console.log('a is ', a) // a is [1, 'test', 3]

This behaviour translate also in the equality operator:

two object are equals if they are the same object, not if they have the same values:

const a = [1];
const b = [1];

a == b // false --> they are two different objects;

const a = [1];
const b = a;

a == b // true

So you cannot compare two arrays values by doing the equal operation like you did:

if(array == newArray)

because you are not comparing the values inside, but their reference (and in this case they are the same reference so it will always be true)

Make sense? :slight_smile:

1 Like