blurstream
blurstream

Reputation: 467

Why does this happen?

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!

Upvotes: 1

Views: 75

Answers (2)

Rinyuaru-Kun
Rinyuaru-Kun

Reputation: 59

@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.

Upvotes: 1

31piy
31piy

Reputation: 23859

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.

Upvotes: 3

Related Questions