jskatas.org Continuously Learn JavaScript. Your Way.

Map: initialize

Initializing a map with values.

initialize a Map

a new Map() is empty, has size=0
const mapSize = new Map(); assert.equal(mapSize, 0);
init Map with [[]] has a size=1
const mapSize = new Map().size; assert.equal(mapSize, 1);
init a Map with [[1]] is the same as map.set(1, void 0)
let map1 = new Map(); let map2 = new Map().set(1, void 0); assert.deepEqual(map1, map2);
init Map with multiple key+value pairs
const pair1 = [1, 'one']; const pair2 = [2, 'two']; const map = new Map(); assert.deepEqual(map, new Map().set(...pair1).set(...pair2));
keys are unique, the last one is used
const pair1 = [1, 'one']; const pair2 = [1, 'uno']; const pair3 = [1, 'eins']; const pair4 = [2, 'two']; const map = new Map([pair3, pair1, pair2, pair4]); assert.deepEqual(map, new Map().set(...pair3).set(...pair4));
init Map from an Object, is a bit of work
let map = new Map(); const obj = {x: 1, y: 2}; const keys = Object.keys(obj); keys.forEach(key => map.set()); assert.deepEqual(map, new Map([['x', 1], ['y', 2]]));

Required Knowledge

Related Katas


Difficulty Level


First Published

22 June 2015


6 tests to solve