Progress pill
Advanced JavaScript

Other collections

  • Set
JavaScript gives us some special collection types that go beyond regular arrays and objects. These include Map and Set.
They help you store and manage groups of values, but they work differently from what you've seen so far.
A Map is a collection of key-value pairs, just like an object. But it has some important differences:
  • The keys can be any value not just strings. The order of the items is preserved.
  • It has built-in methods to make working with it easier.
You create a new map like this:
const myMap = new Map()
This creates an empty map. To add entries to it, use myMap.set(key, value):
myMap.set("name", "Alice")
This adds a key "name" with value "Alice".
You can also use a number as a key:
myMap.set(42, "The answer")
And even an object as a key:
const objKey = { id: 1 } myMap.set(objKey, "Object as key")
That would not work with regular objects, which only allow string keys.
To get a value, use myMap.get(key):
console.log(myMap.get("name")) // Alice console.log(myMap.get(42)) // The answer console.log(myMap.get(objKey)) // Object as key
To check if a key exists, use myMap.has(key):
console.log(myMap.has("name")) // true
To remove a key, use myMap.delete(key):
myMap.delete("name")
To clear the whole map, use myMap.clear():
myMap.clear()
Maps are great for managing large collections of values, because accessing values on a large map gives usually much better performance than on a large object.

Set

A Set is a collection of values only (no keys), where each value must be unique. That means:
  • You can't have the same value twice
  • The values are stored in the order you add them
You create a set like this:
const mySet = new Set()
To add values, use mySet.add(value):
mySet.add(1) mySet.add(2) mySet.add(2) // duplicate, will be ignored
Even though we tried to add 2 twice, the set will only keep one copy.
To check if a value is in the set, use mySet.has(value):
console.log(mySet.has(2)) // true console.log(mySet.has(3)) // false
To remove a value, use mySet.delete(value):
mySet.delete(2)
To clear everything, use mySet.clear():
mySet.clear()
A Set is useful when you want to keep a collection of unique values without having to manually check for duplicates:
const numberArray = [1, 2, 2, 3, 4, 4, 4, 5] const numberSet = new Set(numberArray) console.log(numberSet) // Set(5) { 1, 2, 3, 4, 5 }
The Set avoids the duplicates for you.