Menu
Coddy logo textTech

Size And Is Empty

Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 33 of 65.

Sets provide two useful properties:

  1. size: Returns the number of elements in the Set.
  2. isEmpty(): A custom method we can create to check if the Set is empty.

Here's how to use the size property:

The size property automatically updates whenever elements are added to or removed from a Set — you don't need to do anything extra to keep it current.

const mySet = new Set([1, 2, 3, 4, 5]);
console.log(mySet.size); // 5

mySet.add(6);
console.log(mySet.size); // 6

mySet.delete(1);
console.log(mySet.size); // 5

We can create an isEmpty() method using the size property:

function isEmpty(set) {
  return set.size === 0;
}

const emptySet = new Set();
const nonEmptySet = new Set([1, 2, 3]);

console.log(isEmpty(emptySet));     // true
console.log(isEmpty(nonEmptySet));  // false
challenge icon

Challenge

Easy

Create a function named partyPlanner that takes an array of RSVPs (strings of names). Some people may have RSVP'd multiple times out of excitement. The function should return an object with:

  • uniqueGuests: The number of unique guests attending
  • hasDuplicates: A boolean indicating if anyone RSVP'd more than once
  • isEmpty: A boolean indicating if no one RSVP'd

Cheat sheet

Sets have useful properties for checking size and emptiness:

size property: Returns the number of elements in the Set

const mySet = new Set([1, 2, 3, 4, 5]);
console.log(mySet.size); // 5

isEmpty() method: Custom function to check if a Set is empty

function isEmpty(set) {
  return set.size === 0;
}

const emptySet = new Set();
console.log(isEmpty(emptySet)); // true

Try it yourself

function partyPlanner(rsvps) {
    let guestSet = new Set(rsvps);
  // Write your code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow