jskatas.org Continuously Learn JavaScript. Your Way.

Map: map.set()

Map.prototype.set adds a new element with key and value to a Map.

Map.prototype.set adds a new element with key and value to a Map

simplest use case is set(key, value) and get(key)
let map = new Map(); map.set(); assert.equal(map.get('key'), 'value');
the key can be a complex type too
const noop = function() {}; let map = new Map(); map.set(function() {}, 'the real noop'); assert.equal(map.get(noop), 'the real noop');
calling set() again with the same key replaces the value
let map = new Map(); map.set('key', 'value'); map.set('key', 'value3'); assert.equal(map.get('key'), 'value1');
set() returns the map object, it's chainable
let map = new Map(); map.set(1, 'one') .set(2, 'two') ; assert.deepEqual([...map.keys()], [1,2,3]); assert.deepEqual([...map.values()], ['one', 'two', 'three']);

Related Katas

Map

Difficulty Level

EXPERT

First Published

26 May 2015

Stats

4 tests to solve