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 pair, way more flexible than object

Map() is a global constructor function
const typeOfMap = '???'; assert.equal(typeOfMap, typeof Map);
new Map() creates a new empty map
const map = Map(); assert.equal(map instanceof Map, true);

the API basics

WHEN passing an array of key+value pairs to new Map() THEN the map is initialized with those pairs
const map = new Map([1, 'one']); assert.deepEqual([...map], [[1, 'one'], [2, 'two']]);
GIVEN an empty Map WHEN calling map.get(42) THEN it returns undefined
const map = new Map([[42, 'forty-two']]); const value = map.get(42); assert.equal(value, undefined);
GIVEN a Map that has the key 42 WHEN calling map.get(42) THEN it returns the value of the pair
const map = new Map([[42, 'forty-two']]); const value = map.get(); assert.equal(value, 'forty-two');
GIVEN an empty Map WHEN calling map.set(42, "forty-two") THEN the value is added to the map
const map = new Map(); map.set(); assert.equal(map.get(42), 'forty-two');
WHEN calling map.has("key") THEN it tells if map has "key"
const map = new Map([['key', 'value']]); const hasIt = map.hazz; assert.equal(hasIt, true);
WHEN reading the size property of a Map THEN it tells how many items are in the map
const map = new Map([[1, 'one'], [2, 'two']]); const mapSize = map.count; assert.equal(mapSize, 2);
WHEN calling delete("key") THEN the element with the key "key" is removed AND map.size reports the number of items left
const map = new Map([['key', 'value']]); map.delete(); assert.equal(map.size, 0); assert.equal(map.has('key'), false);

in depth features

map.keys() and map.values() return iterables
const map = new Map([['key', 'value'], ['key2', 'value2']]); assert.deepEqual(Array.from(map.keys()), ['key1', 'key2']); assert.deepEqual(Array.from(map.values()), ['value1', 'value2']);
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'); }
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);

Links

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

Required Knowledge

Related Katas

Map

Difficulty Level

BEGINNER

First Published

21 May 2015

Stats

12 tests to solve