codecks.

Arrays & objects · Output question

JavaScript Set and object identity

Two objects have equal-looking contents. Predict the Set size and whether a third equal-looking object is a member.

const first = { label: "draft" };
const second = { label: "draft" };
const seen = new Set([first, second, first]);
console.log(seen.size);
console.log(seen.has({ label: "draft" }));

What gets logged?

Choose an output before opening the walkthrough, or check your answer in practice mode.

  1. 1
    true
  2. 2
    true
  3. 2
    false
  4. 3
    false
Reveal the answer and execution trace
2
false

A Set compares objects by identity. The repeated first reference is deduplicated, but the new object passed to has is a third identity.

  1. Line 1. first points to one object.
  2. Line 2. second points to a distinct object with the same property value.
  3. Line 3. Adding first a second time leaves the set with two members.
  4. Line 5. The new object literal has never been added to seen.

Reference: Set equality on MDN.