Harmony Collections 2

Simple maps and sets allow you to create a Map with an object as the key. Normally people use Object.create(null) as a map but that limits the keys to strings. The Set constructor is similar and it allows a set containing objects. Neither of these currently support a way of iteration since iteration is planned to be covered by the iteration proposal which is not yet implemented.

var map = new Map;
map.set('a', 'A');
map.get('a');  // 'A'
var b = {};
map.set(b, 'B');
map.get(b);  // 'B'
map.has(b);  // true
var set = new Set;
set.add('a');
set.has('a');  // true
var b = {};
set.add(b);
set.has(b);  // true

Harmony also provides another kind of map called WeakMap. This has the same API as Map but it has different GC semantics. A normal Map using an object as a key prevents the object from being garbage collected but with a WeakMap the object can be garbaged collected. This is useful when you associate data with someone else’s object.

var map = new WeakMap;
map.set(elementA, 'A');
map.get(elementA);  // 'A'
map.set(elementB, 'B');
map.get(elementB);  // 'B'
map.has(elementB);  // true

In the above example, if the element is removed from the DOM and the script has no references to it the element can be garbage collected.

Unlike Map and Set, WeakMap will never have a way to iterate over the items since that would expose the GC behavior.