1

When I run this function:

var isPalindrome = function (string) {
  if (string == string.split('').reverse().join('')) {
    console.log(string + ' is palindrome.');
  }
  else {
    console.log(string + ' is not palindrome.');
  }
}

console.log(isPalindrome("phone")) ---> "phone is not a palindrome"

console.log(isPalindrome("anna")) ---> "anna is a palindrome"

It works. However, I am completely puzzled as to why this function will not do the same thing?

var isPalindrome = function(string) {
  var stringArray = string.split("");
  var reverseStringArray = string.split("");
  reverseStringArray.reverse();

  if (stringArray == reverseStringArray) {
    console.log("Victory!")
  } else {
    console.log("Defeat")
  }
}

console.log(isPalindrome("phone")) ---> "Defeat"

console.log(isPalindrome("anna")) ---> "Defeat"

Any ideas?

user3007294
  • 931
  • 1
  • 14
  • 33
  • 3
    You're comparing two different arrays, which are compared by reference, unlike strings which are compared character by character – Andrew Whitaker Jun 23 '15 at 13:57
  • Hmmm okay. Because when I do something similar in Ruby, it works. Is this just because it's Javascript? So two arrays most likely will never be the same in Javascript? – user3007294 Jun 23 '15 at 13:59
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness – Kijewski Jun 23 '15 at 14:00
  • Thanks a ton everyone. This helps a lot. I had no idea arrays in Javascript operated like this. – user3007294 Jun 23 '15 at 14:01
  • 2
    *"Is this just because it's Javascript?"* - There are a number of languages that handle arrays in this fashion. Used on arrays, `==` asks "Are these the same object instance?", which is not the same equality test as "Do these two objects contain the same data?". – nnnnnn Jun 23 '15 at 14:01

0 Answers0