DEV Community

Cover image for JavaScript Quiz Question #2: A Set of Objects
Nick Scialli (he/him)
Nick Scialli (he/him)

Posted on

JavaScript Quiz Question #2: A Set of Objects

Consider the following Set of objects spread into a new array. What gets logged?

const mySet = new Set([{ a: 1 }, { a: 1 }]);
const result = [...mySet];
Enter fullscreen mode Exit fullscreen mode

A) [{a: 1}, {a: 1}]
B) [{a: 1}]

Put your answer in the comments!

Top comments (4)

kenbellows profile image
Ken Bellows

A, because separate objects are not deduped by a Set, even if they happen to have an identical structure and values. If you wanted it to log B, you'd have to do this:

const o = {a: 1}
const mySet = new Set([o, o])
const result = [...mySet]

Here the object does get deduped because it's the same exact object instance twice, not two different object instances that looks the same.

timhlm profile image


This is because in JS Objects are passed by reference instead of value.

Just for fun, one of my first packages on npm was to make a superset of Set that included functionality allows you to do this by reference.

dreiv profile image
Andrei Voicu


honghuynhit profile image
Huynh HD