10

Why is [] !== [] in JavaScript?

I read through https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness but I could not find anything that explains this.

Edit: I don't think this question or this question is an exact duplicate of mine. It asks about the == operator which just behaves crazy. The answer is an answer to my question but it's not the same question.

fahrradflucht
  • 1,563
  • 3
  • 14
  • 22
  • 2
    It compares for being the same object rather than equivalence. – Ultimater Oct 28 '16 at 21:12
  • 2
    I thought the same thing at first, but `[] == []` and `[] === []` both return false. – HTTP 501 Oct 28 '16 at 21:13
  • 1
    Because lists are actually objects and objects are never equal unless two variables are referencing the same object – Nick is tired Oct 28 '16 at 21:13
  • It's because they aren't the same object. It only compares the references and not the content – Johannes Merz Oct 28 '16 at 21:13
  • 1
    http://dorey.github.io/JavaScript-Equality-Table/, as per the link in the page you cite. – Marc B Oct 28 '16 at 21:13
  • @Bergi I now know that in this case `==` and `===` behave the same but when I was searching I didn't and a lot of people probably think the same. So the duplicate you provided was about `==` which is a different thing if you don't already know the answer... – fahrradflucht Jun 24 '18 at 09:01

3 Answers3

9

That does a reference check on the two array literals to see if they are the same instance. The fact that you have two literals means that you are constructing two separate arrays, therefore the reference check returns false. This would return true:

var a = []
var b = a

//b === a

This is because we have two references to the same array.

Lew
  • 1,248
  • 8
  • 13
4

[] creates a new (and empty) array each time you write it. You are comparing two arrays, regardless of their content, their pointer (or reference) are being compared.

var array = [];
var anotherArray = array; // these two will point to the same array, so they are equal


array === anotherArray; // true
array === []; // false


array.push('something');
anotherArray.length; // 1
Aᴍɪʀ
  • 7,623
  • 3
  • 38
  • 52
3

Because [] is an object, and a comparison of objects only returns true when both sides of the comparison point to the exact same object. You have created two separate objects, so they aren't equal.

var x = []
var y = x
var z = []

x == x // true
x == y // true
x == z // false
Mogzol
  • 1,405
  • 1
  • 12
  • 18