Size And Is Empty
Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 33 of 65.
Sets provide two useful properties:
size: Returns the number of elements in the Set.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); // 5We 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)); // falseChallenge
EasyCreate 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 attendinghasDuplicates: A boolean indicating if anyone RSVP'd more than onceisEmpty: 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); // 5isEmpty() 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)); // trueTry it yourself
function partyPlanner(rsvps) {
let guestSet = new Set(rsvps);
// Write your code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String FundamentalsIterate Over StringsTemplate LiteralsString MethodsRecap - String Weaver4JSON Part 2
Iterate Over JSONNested JSONJSON Optional ChainingShallow And Deep CopyRecap - Bicycle ShopRecap - Solar System10Manage Festival System
Project OverviewAdd Movies & Venues2Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays5Sets Part 1
What Is A Set?Iterating Over SetsAdding An ElementRemoving An ElementChecking If An Element ExistsSize And Is EmptyCopy And ClearRecap - Basic Of Sets8Arrays Interesting Topics
Array DestructuringSpread Syntax in ArraysSparse ArraysRecap - Arrays Workshop3JSON Part 1
What is a JSON?Check If Key ExistsObject MethodsThe Spread Operator Part 1The Spread Operator Part 2Remove KeysRecap - JSON Manipulate Keys