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];
console.log(result);
Enter fullscreen mode Exit fullscreen mode

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

Put your answer in the comments!

Top comments (4)

Collapse
 
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]
console.log(result)

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

Collapse
 
timhlm profile image
moth

A!

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.

npmjs.com/package/spicy-set

Collapse
 
dreiv profile image
Andrei Voicu

B

Collapse
 
honghuynhit profile image
Huynh HD

A