What are `Set`s and `Map`s and how are they used?
Topics
JavaScript
TL;DR
Sets and Maps are built-in JavaScript objects that help manage collections of data. A Set is a collection of unique values, while a Map is a collection of key-value pairs where keys can be of any type. Sets are useful for storing unique items, and Maps are useful for associating values with keys.
Set
What is a Set?
A Set is a collection of values where each value must be unique. It is similar to an array but does not allow duplicate values.
How to create a Set
You can create a Set using the Set constructor:
Common methods
add(value): Adds a new element with the given value to theSet.delete(value): Removes the element associated with the value.has(value): Returns a boolean indicating whether the value exists in theSet.clear(): Removes all elements from theSet.size: Returns the number of elements in theSet.
Example usage
Map
What is a Map?
A Map is a collection of key-value pairs where keys can be of any type, including objects, functions, and primitives.
How to create a Map
You can create a Map using the Map constructor:
Common methods
set(key, value): Adds or updates an element with the specified key and value.get(key): Returns the value associated with the key.delete(key): Removes the element associated with the key.has(key): Returns a boolean indicating whether the key exists in theMap.clear(): Removes all elements from theMap.size: Returns the number of elements in theMap.
Example usage
Further reading
Exercises
Check your understanding
Beta