Sets in JavaScript
October 20th, 2024 10:15 PM Mr. Q Categories: JavaScript
Sets are a built-in object type that allows you to store unique values of any type, whether primitive or object references. Unlike arrays, sets automatically ensure that no duplicate values are stored, making them particularly useful for maintaining collections of unique items.
Command Description
- Creating and Using Sets:
- You can create a new set using the
new Set()
constructor.
- Unique Value Methods:
- .add(value): Adds a new unique value to the set. If the value already exists, it will not be added again.
- .delete(value): Removes the specified value from the set. Returns
true
if the value was successfully removed, orfalse
if it was not found. - .has(value): Checks if the set contains the specified value. Returns
true
orfalse
. - .clear(): Removes all values from the set.
- Iterating Over Sets:
- You can use
forEach()
orfor...of
to iterate over the unique values in a set.
Sample Code
Copy001// Creating a new set
002let uniqueItems = new Set();
003
004// Adding unique values with add()
005uniqueItems.add('sword');
006uniqueItems.add('shield');
007uniqueItems.add('potion');
008uniqueItems.add('sword'); // Attempt to add a duplicate
009
010console.log(uniqueItems);
011// Set(3) { 'sword', 'shield', 'potion' }
012
013// Checking for a value with has()
014console.log(uniqueItems.has('shield')); // true
015console.log(uniqueItems.has('axe')); // false
016
017// Removing a value with delete()
018uniqueItems.delete('potion');
019console.log(uniqueItems);
020// Set(2) { 'sword', 'shield' }
021
022// Clearing all values in the set
023uniqueItems.clear();
024console.log(uniqueItems); // Set(0) {}
025
026// Re-adding unique values for iteration demonstration
027uniqueItems.add('magic wand');
028uniqueItems.add('staff');
029
030// Iterating over sets
031uniqueItems.forEach(value => {
032 console.log(`Item: ${value}`);
033});
034
035// Alternative iteration using for...of
036for (let item of uniqueItems) {
037 console.log(`Item: ${item}`);
038}
Output
Copy001Set(3) { 'sword', 'shield', 'potion' }
002true
003false
004Set(2) { 'sword', 'shield' }
005Set(0) {}
006Item: magic wand
007Item: staff
008Item: magic wand
009Item: staff
Use Case
- Unique Item Collection: Sets are perfect for managing collections of unique game items, such as inventory systems, where you want to ensure that players cannot have duplicate items (e.g., no two identical swords).
- Performance: Checking for the existence of a value (using
.has()
) in a set is generally faster than in an array because sets utilize hash tables for storage. This makes sets a more efficient choice when you frequently need to check for the presence of items. - Dynamic Data Management: Sets are useful for dynamic situations where the collection of items may frequently change, such as tracking active players in a game or maintaining a list of completed quests. Their ability to handle unique values effortlessly makes them an ideal choice for scenarios requiring quick insertions and deletions while keeping data integrity intact.