3

enter image description here

Can anyone describe the picture above? It is the screenshot of my Chrome dev-tool console.

Sejin Jeon
  • 338
  • 2
  • 4
  • 17
  • 3
    Hint: What does `[].toString()` return? – Barmar Feb 10 '18 at 07:58
  • Then why does `[] == []` returns false? – Sejin Jeon Feb 10 '18 at 07:59
  • 1
    Because [this](https://stackoverflow.com/questions/40313263/why-is-in-javascript). Also read [this](https://stackoverflow.com/questions/42604993/how-can-an-object-be-equal-to-an-empty-string). – user202729 Feb 10 '18 at 08:00
  • 2
    Array are objects, comparing two objects always returns false since they are 2 different "things". When `doing [] == ""`, a cast of the array to a string is done by the js interpreter. Then the 2 strings are compared. – Pierre Feb 10 '18 at 08:01
  • @user202729 I already know that. This is the reason I typed three different things. First one returns false because their references are different, and third one returns true because they contains the same data. But then why second one returns false while they contains the same data and even same type? They are compared with `==`, not `===`. – Sejin Jeon Feb 10 '18 at 08:03
  • [This](https://stackoverflow.com/questions/7713794/in-javascript-why-is-1-2-1-2-or-a-1-a-1-false) too. (side note: remember to post code instead of image next time) – user202729 Feb 10 '18 at 08:05
  • @trincot Where does that explain `[] == ""`? – Barmar Feb 10 '18 at 08:05
  • @Barmar In the second question the OP did perform the comparison `[] == ""`. If you feel that the answer does not explain that you can post another answer. – user202729 Feb 10 '18 at 08:07
  • 1
    Also the third one explains it at the bottom of the accepted answer. There are many Q&A that answer one of these equalities. – trincot Feb 10 '18 at 08:09

1 Answers1

8

Because of JavaScript coercion.

[] is loosely equated to "" and thus coerced to string using [].toString() which is equal to "".

And why does [] == [] and [] === [] return false:

the == and === comparison rules if you’re comparing two non-primitive values, like objects (including function and array). Because those values are actually held by reference, both == and === comparisons will simply check whether the references match, not anything about the underlying values.

var a = [1,2,3];
var b = [1,2,3];

var c = "1,2,3";

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

arrays are by default coerced to strings by simply joining all the values with commas (,) in between.

void
  • 36,090
  • 8
  • 62
  • 107
  • What did you mean by "the == and === comparison rules"? – nCardot Aug 28 '21 at 21:39
  • 1
    @nCardot when you do a strict comparison the data types are also compared but if it is not a strict comparison then the values coerce to come to similar data type. This thing has certain rules by which the values coerce. You can read about it more on mdn. – void Sep 14 '21 at 19:06