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
// Creating a new set
let uniqueItems = new Set();
// Adding unique values with add()
uniqueItems.add('sword');
uniqueItems.add('shield');
uniqueItems.add('potion');
uniqueItems.add('sword'); // Attempt to add a duplicate
console.log(uniqueItems);
// Set(3) { 'sword', 'shield', 'potion' }
// Checking for a value with has()
console.log(uniqueItems.has('shield')); // true
console.log(uniqueItems.has('axe')); // false
// Removing a value with delete()
uniqueItems.delete('potion');
console.log(uniqueItems);
// Set(2) { 'sword', 'shield' }
// Clearing all values in the set
uniqueItems.clear();
console.log(uniqueItems); // Set(0) {}
// Re-adding unique values for iteration demonstration
uniqueItems.add('magic wand');
uniqueItems.add('staff');
// Iterating over sets
uniqueItems.forEach(value => {
console.log(`Item: ${value}`);
});
// Alternative iteration using for...of
for (let item of uniqueItems) {
console.log(`Item: ${item}`);
}
Output
Set(3) { 'sword', 'shield', 'potion' }
true
false
Set(2) { 'sword', 'shield' }
Set(0) {}
Item: magic wand
Item: staff
Item: magic wand
Item: 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.