jskatas.org Continuously Learn JavaScript. Your Way.

Map: Basics

A Map holds key-value pairs, the key can even be a complex value.

Map is a key/value map

Map is a global constructor function
const typeOfMap = '???'; assert.equal(typeOfMap, typeof Map);
provides new Map().set() to add key+value pair, get() to read it by key
const map = new Map(); map.set('key', null); const value = map.get(); assert.equal(value, 'value');
has() tells if map has the given key
const map = new Map(); map.set('key', 'value'); const hasIt = map.hazz; assert.equal(hasIt, true);
delete() deletes the element given by the key AND map.size reports the number of items
const map = new Map([['key', 'value']]); map.delete('key'); assert.equal(map.size, 0);
keys() and values() return iterables of the keys and values
const map = new Map([['key', 'value']]); assert.deepEqual(Array.from(map.keys()), ['key']); assert.deepEqual(Array.from(map.values()), ['value']);
a map can be iterated over using for-of
const map = new Map([ ['uno', 'one'], ]); for (let [key, value] of map) { assert.equal(key, 'one'); assert.equal(value, 'uno'); }
a map is iterable
const map = new Map(); map.set('1', 'one'); map.set('2', 'two'); const mapAsArray = map; // hint: kata #29 http://tddbin.com/#?kata=es6/language/array-api/from assert.deepEqual(mapAsArray, [['1', 'one'], ['2', 'two']]);
complex types can be keys
const obj = {x: 1}; const otherObj = {x: 1}; const map = new Map(); map.set(obj, ''); map.set(otherObj, ''); assert.equal(map.has(otherObj), false);


MDN page about Map.
The chapter in the specification, with all details about Map.