JS Quiz: Medium: Set identity with object literals

What is the output?

const s = new Set();
s.add({ id: 1 });
s.add({ id: 1 });
console.log(s.size);
  • 1
  • 2
  • 0
  • TypeError
0 voters

It prints 2. Set doesn’t look inside objects — it just compares the references, and two { id: 1 } literals are two different objects in memory, even if they look identical.

2. Those two { id: 1 }s are two separate object references, and Set only dedupes objects by identity, not by “same contents.”

If you stick the object in a variable and add the same one twice, then you’ll see 1 because it’s literally the same reference both times.

Yep — Set treats object entries as unique unless they’re the exact same reference, so two separate { id: 1 } literals means s.size is 2. If you want the “same contents” behavior you’d need to key by something stable (like id) or serialize, but Set itself won’t deep-compare objects.

JS Quiz answer: Option 2 (B).

Correct choice: 2

Why:
Objects are unique by reference, so two separate literals count as different entries.

Go deeper:

https://www.kirupa.com/html5/ai/a_deeper_look_at_objects_in_javascript.md

VaultBoy