0

I'm learning JS and had to come up with a function to check if a certain string is a palindrome. I managed to get it right with:

function isPalindrome(word) {
    return word == word.split('').reverse().join('');
}

However, my first attempt was:

function isPalindrome(word) {
    return word.split("") === (word.split("").reverse());
}

But this does not work. What this second function does is get the string and make an array out of it, then compare that to the string as an array but reversed. If I console.log() both sides I get the same array (in the case of a palindrome like "level") so why does this always evaluate to false?

M0nst3R
  • 5,186
  • 1
  • 23
  • 36
cesarcarlos
  • 1,271
  • 1
  • 13
  • 33
  • 2
    The arrays may look the same, but they are not the exact same array in memory. For objects to be equal, they must both point to the same actual object. Just looking the same isn't enough. – Niet the Dark Absol Oct 12 '17 at 15:33
  • 1
    In other words, they are two different arrays with the same content. – JJJ Oct 12 '17 at 15:34
  • 2
    @JJJ I don't think that's a helpful duplicate target. It doesn't explain *why* the comparison fails, only how to successfully compare the contents of two arrays. – Mike Cluck Oct 12 '17 at 15:37
  • 2
    @MikeC I believe [this one](https://stackoverflow.com/questions/30820611/javascript-arrays-cannot-equal-each-other) would be better, as it explains why and links to the duplicate mentioned above as well – George Oct 12 '17 at 15:40
  • @George Your link indeed explains the issue. Thanks! Apologies for the duplicate. – cesarcarlos Oct 12 '17 at 15:44

0 Answers0