Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

William Hurst
William Hurst
25,074 Points

stevenS = stevenJ; set size

The Set

let classroom = new Set();

let stevenJ = { name: 'Steven', age: 22 },
    sarah = { name: 'Sarah', age: 23 },
    stevenS = stevenJ;

classroom.add(stevenJ);
classroom.add(sarah);
classroom.add(stevenS);

console.log('classroom size:', classroom.size);

console.log('classroom size:', classroom.size); outputs:

classroom size: 2

Check if a value exists using has:

if (classroom.has(stevenJ)) console.log('stevenJ is in the classroom');
if (classroom.has(sarah)) console.log('sarah is in the classroom');
if (classroom.has(stevenS)) console.log('stevenS is in the classroom');

Outputs:

stevenJ is in the classroom
sarah is in the classroom
stevenS is in the classroom

Why do 3 values exist with has, but using size shows 2 values?

1 Answer

Why do 3 values exist with has, but using size shows 2 values?

Because stevenS = stevenJ and Set.prototype.size returns unique elements in the Set.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/size