0

const arr1 = [1,2,3];
const arr2 = [1,2,3];
const str = "1,2,3";

console.log(arr1 == arr2); // Why it's false
console.log(arr1 == str); // Why it's true

So, why the array to array comparison prints "false" and an array to string comparison prints "true"

Suyash Madhav
  • 49
  • 1
  • 2
  • 9
  • 6
    Array values are *references* to objects. Object comparisons are made on the basis of strict object reference equality; two distinct objects never compare as equal. The `==` operator handles a comparison between an object and a string by first calling `.toString()` on the object; in the case of an array, that's like calling `.join(",")`. – Pointy Oct 29 '18 at 13:01
  • 1
    Thank you so much for this question! Not sure why it was closed as a duplicate because the question that the closure notice points to may have an answer, but I would never have found it without this thread (as that one is asking a way more general one). Would also love to hear legitimate reasons for the downvotes (other than herd mentality drive-by actions) because the question is succinct, has the necessary examples to support it so clearly not a low quality writing. – toraritte Feb 05 '22 at 03:22

1 Answers1

2

In JavaScript, two object instances are never equal, even if they have the same content.

See this nice post about how to compare arrays: How to compare arrays in JavaScript?

ScottBro
  • 309
  • 1
  • 12