Welcome, JavaScript adventurers! This chapter delves into the exciting realm of Sets and Maps, two powerful object-like collections that enhance your data storage and manipulation capabilities. We'll explore their functionalities, use cases, and advanced applications, equipping you to make informed decisions when working with collections in JavaScript.
new Set()
constructor or by wrapping an iterable object (like an array) containing duplicates.
const fruits = new Set(["apple", "banana", "orange", "banana"]);
console.log(fruits); // Output: Set { "apple", "banana", "orange" }
const numbers = new Set([1, 1, 2, 3, 3]);
console.log(numbers); // Output: Set { 1, 2, 3 }
fruits
Set with duplicate values. In the resulting Set, “banana” appears only once, as Sets eliminate duplicates.numbers
Set removes duplicates from the original array.add(value)
: Adds a new element to the Set.has(value)
: Checks if a specific value exists in the Set (returns true
or false
).delete(value)
: Removes a specific element from the Set (returns true
if successful, false
if not found).size
: Returns the number of elements in the Set.
const colors = new Set(["red", "green", "blue"]);
colors.add("purple");
console.log(colors.has("red")); // Output: true
colors.delete("green");
console.log(colors.size); // Output: 2
colors
Set using add()
.has("red")
checks if “red” exists (it does).delete()
.size
confirms there are now two elements in the Set.
const studentInfo = new Map([
["name", "Alice"],
["age", 25],
[true, "active"] // Key can be any data type
]);
console.log(studentInfo.get("name")); // Output: Alice
studentInfo
Map using an array of key-value pairs.true
).get()
.set(key, value)
: Adds a new key-value pair to the Map.get(key)
: Retrieves the value associated with a specific key.has(key)
: Checks if a specific key exists in the Map.delete(key)
: Removes a key-value pair from the Map.size
: Returns the number of key-value pairs in the Map.
const countries = new Map();
countries.set("US", "United States");
countries.set("JP", "Japan");
console.log(countries.get("US")); // Output: United States
countries.delete("JP");
console.log(countries.size); // Output: 1
countries
Map and add key-value pairs using set()
. Keys are country codes (“US”, “JP”), and values are full country names.get("US")
retrieves the value for the key “US”.delete()
.size
confirms there’s only one key-value pair left.
const subscribedUsers = new Set([1, 2, 3]);
function isSubscribed(userId) {
return subscribedUsers.has(userId);
}
console.log(isSubscribed(2)); // Output: true
subscribedUsers
Set to store user IDs.isSubscribed
function checks if a provided userId
exists in the Set using has()
, offering a fast lookup for membership.
const studentData = new Map();
const student1 = { name: "Alice", age: 25 };
studentData.set(student1, ["Math", "Physics"]);
console.log(studentData.get(student1)); // Output: ["Math", "Physics"]
studentData
Map. Keys can be any data type, so here, we use a student object (student1
) as the key.student1
is an array of courses using set()
.student1
using get()
. This allows us to associate complex data with unique identifiers.Sets and Maps provide powerful alternatives to traditional arrays and objects in JavaScript. By understanding their unique features and use cases, you can make informed decisions about data storage and manipulation, leading to more efficient and flexible code. Remember, Sets excel at handling unique values and fast membership checks, while Maps shine when dealing with key-value pairs where keys can be any data type. Happy exploring the world of Sets and Maps Happy coding !❤️