# ES6 Maps and Sets
There were two new types of Objects added in ES6 - Map
and Set
. A Set
is like an Array
with no duplicate values. A Map
is like an Object
with unique keys, the insertion order is remembered and any value, not just a string, can be used as the key.
Here is a sample bit of code creating a Set
and adding items.
let mySet = new Set();
mySet.add('new value');
mySet.add('new value');
mySet.add('something else');
mySet.add('new value');
mySet.has('new value'); //true
mySet.forEach((item) => {
console.log(item);
}); //output will be "new value" "something else"
//"new value" was only added once
mySet.delete('new value'); //since every value is unique we can delete using the value
mySet.size; // 1 - only "something else" left
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
MDN reference for Sets (opens new window)
And here is a bit of sample code showing how to create a Map
and interact with it.
let myMap = new Map();
let obj = { abc: 123 };
myMap.set('first', 'some value');
myMap.set(obj, 'another value');
myMap.set(false, 'a third value');
myMap.has(false); //true
myMap.has('first'); //true
myMap.get(obj); // "another value"
myMap.delete(false); //delete the item with the key false.
myMap.forEach((item, key) => {
console.log(`The key is ${key} and the value is ${item}`);
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
MDN reference for Maps (opens new window)
TIP
Important to note that BOTH Map
s and Set
s are iterable, unlike Object
s.