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 examplelet mySet = new Set([1, 2, 3, 3]); // Set {1, 2, 3} (duplicate values are not added)mySet.add(4);console.log(mySet); // Set {1, 2, 3, 4}// Map examplelet myMap = new Map();myMap.set('key1', 'value1');myMap.set('key2', 'value2');console.log(myMap.get('key1')); // 'value1'
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:
let mySet = new Set([1, 2, 3, 3]);console.log(mySet); // Set {1, 2, 3}
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
let mySet = new Set();mySet.add(1);mySet.add(2);mySet.add(2); // Duplicate value, will not be addedconsole.log(mySet.has(1)); // trueconsole.log(mySet.size); // 2mySet.delete(1);console.log(mySet.has(1)); // falsemySet.clear();console.log(mySet.size); // 0
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:
let myMap = new Map();myMap.set('key1', 'value1');myMap.set('key2', 'value2');console.log(myMap); // Map { key1: "value1", key2: "value2" }
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
let myMap = new Map();myMap.set('key1', 'value1');myMap.set('key2', 'value2');console.log(myMap.get('key1')); // 'value1'console.log(myMap.has('key2')); // trueconsole.log(myMap.size); // 2myMap.delete('key1');console.log(myMap.has('key1')); // falsemyMap.clear();console.log(myMap.size); // 0