Beyond Arrays and Objects: Exploring Sets and Maps in JavaScript
We all know the classic data structures in JavaScript: arrays for ordered lists and objects for key-value pairs. But what if you need to ensure unique values or want a more efficient way to search and retrieve data? That’s where Sets and Maps come in, offering unique capabilities beyond the usual suspects.
The Trouble with Arrays: Uniqueness and Searching
Imagine you’re building a shopping cart feature. You want to keep track of the items a user adds, but you don’t want duplicates. With a regular array, you’d have to manually check for existing items before adding new ones, making the code cumbersome and inefficient.
let cart = [];
function addItemToCart(item) {
if (!cart.includes(item)) {
cart.push(item);
}
}
Sets: Ensuring Uniqueness with Elegance
Sets are like special arrays that only allow unique values. Adding a duplicate item has no effect.
Let’s rewrite our shopping cart example using a Set:
let cart = new Set();
function addItemToCart(item) {
cart.add(item); // Duplicates are ignored automatically
}
Much cleaner, right? Sets also provide handy methods like has
to check for…