1

The title pretty much says it all, but here it is written out:

b = [1, 2, 3, 4];
c = [...b];

b === c; //false

Why?

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Collin
  • 254
  • 1
  • 9
  • 5
    `[] !== []`. Two arrays are two unique objects. To compare, you need to iterate. – elclanrs Jan 13 '18 at 18:48
  • 2
    @elclanrs To an expert it's obvious this is a duplicate of the mentioned question. To someone who is asking the question it is distinct: you can see this because there is no mention of the `...` operator on the linked page. It's subtle enough I can see it staying closed or being reopened but my vote is for re-opening. – Levi Morrison Jan 13 '18 at 18:59
  • @LeviMorrison Note, spread syntax `...` is not an operator https://stackoverflow.com/questions/37151966/what-is-spreadelement-in-ecmascript-documentation-is-it-the-same-as-spread-oper – guest271314 Jan 13 '18 at 19:04
  • @guest271314 Fair enough; I invoked the spec in my answer so I deserve to be nitpicked. – Levi Morrison Jan 13 '18 at 19:08

2 Answers2

4

It's how regular array identity / strict equality comparison works. Remember that arrays are objects:

The Strict Equality Comparison Algorithm

The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:

  1. If Type(x) is different from Type(y), return false.
  2. If Type(x) is Undefined, return true.
  3. If Type(x) is Null, return true.
  4. If Type(x) is Number, then
    • If x is NaN, return false.
    • If y is NaN, return false.
    • If x is the same Number value as y, return true.
    • If x is +0 and y is −0, return true.
    • If x is −0 and y is +0, return true.
    • Return false.
  5. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions); otherwise, return false.
  6. If Type(x) is Boolean, return true if x and y are both true or both false; otherwise, return false.
  7. Return true if x and y refer to the same object. Otherwise, return false.

NOTE This algorithm differs from the SameValue Algorithm (9.12) in its treatment of signed zeroes and NaNs.

The ... has no impact. If we assign the same literals to both we can see this:

b = [1, 2, 3, 4];
c = [1, 2, 3, 4];

b === c; //false

This is because each [] will create a new array, even if it uses a spread in it.

Levi Morrison
  • 19,116
  • 7
  • 65
  • 85
1

c is a new Array instance, not the same object.

You can use .every() to check if every element at index of b has the same value of element at index c

let bool = b.every((n, index) => c[index] === n)
guest271314
  • 1
  • 15
  • 104
  • 177
  • See also [3.3.20.\[SameObject\]](https://heycam.github.io/webidl/#SameObject). For example `const synth = window.speechSynthesis; window.speechSynthesis === synth // should always be true` – guest271314 Jan 13 '18 at 18:56