ES6 Data Structures
This is the part of a series of blogs on the new features on the upcoming ECMAScript 6 (ES6) specification which JavaScript implements.
In this blog we focus on the new data structures introduced in ES6, specifically keyed collections.
Keyed Collections #
Keyed collections are object data structures that represent collections of data which use keys. Keyed collections contain elements which can be iterated in the order of insertion. ES6 includes these new data structures to handle your complex javascript applications without having to develop the building blocks yourself to save time, standardize, as well as provide a more optimized garbage collection strategy.
Set #
- iterate elements in order
- unique elements
- accepts
NaN
orundefined
- key and value are the same
var mySet = new Set();
mySet.add("cat");
mySet.add(24);
mySet.add("bunny");
for (let item of mySet) console.log(item);
// "cat"
// 24
// "bunny"
Map #
- iterate elements in order
- key/value pairing
- unique keys
- accepts
NaN
orundefined
Differences between Object and Map #
- object has a prototype so there are default keys
- can be bypassed using
map = Object.create(null)
- can be bypassed using
- object keys are string whereas map keys can be anything
- map keeps track of size
- use maps over objects when keys are unknown until run time
- use objects when there is logic that operates on individual elements
var myMap = new Map();
myMap.set("cat", "bengal");
myMap.set(24, 12);
myMap.set(NaN, "not a number");
myMap.get(NaN); // "not a number"
for (var [key, value] of myMap) console.log(key + " - " + value);
// "cat - bengal"
// "24 - 12"
// "NaN - not a number"
WeakSet #
- iterate through providing keys only
- not enumerable
- unique object references
- only accept objects
Differences between Set and WeakSet #
- WeakSets are collections of object types only
- references to objects in the collection are held weakly
var myWeakSet = new WeakSet();
var foo = {};
var bar = {};
myWeakSet.add(foo);
myWeakSet.has(bar); // false
myWeakSet.has(foo); // true
myWeakSet.delete(foo);
myWeakSet.add({ kobe: 24 }); // But because the added object has no other references, it will not be held in the set
WeakMap #
- iterate through providing keys only
- not enumerable
- unique object or function references
- does not accept primitive data types as keys
var myWeakMap = new WeakMap();
var obj1 = {};
var obj2 = function(){};
myWeakMap.set(obj1, "cat");
myWeakMap.set(obj2, 24);
myWeakMap.has(obj1); // true
myWeakMap.get(obj2); // 24
myWeakMap.delete(obj1);