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.
Reveal the answer and execution trace
2
falseA Set compares objects by identity. The repeated first reference is deduplicated, but the new object passed to has is a third identity.
- Line 1. first points to one object.
- Line 2. second points to a distinct object with the same property value.
- Line 3. Adding first a second time leaves the set with two members.
- Line 5. The new object literal has never been added to seen.
Reference: Set equality on MDN.