2

Running this code produces results as in comments, but why is it happening?

let a = [1,2,3];
let b = [1,2,3];
let c = '1,2,3';
a == c; // true
b == c; // true
a == b; // false

I noticed if you change the previous code with the following, final result changes:

let a = [1, 2, 3];
let b = [1, 2, 3];
let c = '1, 2, 3';
a == c; // false
b == c; // false
a == b; // false

Thank you!

blurstream
  • 429
  • 3
  • 13
  • 1
    Because `a==c` and `b==c` convert the arrays to strings, the third compares references of the two arrays (which are not equal). See [here](https://stackoverflow.com/questions/7625144/implicit-data-type-conversion-in-javascript-when-comparing-integer-with-string-u) – Federico klez Culloca May 04 '18 at 15:32
  • 1
    Use === for strict comparison –  May 04 '18 at 15:33
  • Forced same type. when comparing primitive elements like strings, numbers or booleans to complex elements like objects, functions or arrays, the latter will be cast to the nearest primitive (string). When comparing complex elements, you are actually checking if the two sides are references to the same elements (instead of whether the objects looks the same). – Emil S. Jørgensen May 04 '18 at 15:35
  • 1
    Are you asking why `[1,2,3] == '1,2,3'`, or why `[1,2,3] != [1,2,3]`? That's two separate questions. – Bergi May 04 '18 at 15:42
  • @Bergi two separate questions, both of which are answered by "don't use broken language features" ;) – Patrick Roberts May 04 '18 at 16:11
  • @PatrickRoberts I was thinking of "…which are answered by separate duplicates" :-) Mostly https://stackoverflow.com/q/7314635/1048572 – Bergi May 04 '18 at 16:23

2 Answers2

3

Please see this article which describes the different types of equality checks in JavaScript.

a == c; // true
b == c; // true

Both of the above return true because == causes the array to convert to its string equivalent using its toString method (as it is being compared to a string using == operator), which returns "1,2,3". Clearly "1,2,3" is equal to "1,2,3".

a == b; // false

The above returns false because a and b are two different arrays and JavaScript compares them by references instead of traversing each element and comparing those individually or by converting them to equivalent strings.

31piy
  • 23,323
  • 6
  • 47
  • 67
1

@blurstream The thing is that the implicit conversion from array to string changes the test from "[1,2,3]" == "[1,2,3]" without the spaces to "[1,2,3]" == "[1, 2, 3]" with the spaces. That's why it changes.

The array [1, 2, 3] is understood by JavaScript as [1,2,3] without the spaces. That changes the test!

More specifically, that changes from "[1,2,3]" == "[1,2,3]", which returns true, to "[1,2,3]" == "[1, 2, 3]", which returns false.

P.S: I didn't comment back and instead posted an answer because of my lack of reputation here, please forgive me.