3

enter image description here

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

9
  • 3
    Hint: What does [].toString() return? Commented Feb 10, 2018 at 7:58
  • Then why does [] == [] returns false? Commented Feb 10, 2018 at 7:59
  • 1
    Because this. Also read this. Commented Feb 10, 2018 at 8: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. Commented Feb 10, 2018 at 8:01
  • 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. Commented Feb 10, 2018 at 8:09

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

What did you mean by "the == and === comparison rules"?
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.