We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Maps

JavaScript also offers (as of recently) support for maps: collections of key-value pairs. Map keys are unique, so adding a key that already exists will replace its value. You can set and delete entries dynamically:

const map = new Map();
map.set("bertholdt", "shifter");
map.set("reiner", "warrior");
map.set("annie", "shifter");
map.set("bertholdt", "colossal titan");
console.log(map);
// Map { 'bertholdt' => 'colossal titan', 'reiner' => 'warrior', 'annie' => 'shifter' }

map.delete("annie");
console.log(map);
// Map { 'bertholdt' => 'colossal titan', 'reiner' => 'warrior' }

Maps can be constructed from any iterable. Maps are iterable, so that means the Map constructor can accept a map:

const originalMap = new Map();
originalMap.set("bertholdt", "shifter");
const mapCopy = new Map(originalMap);
console.log(mapCopy);
// Map { 'bertholdt' => 'shifter' }

Assignment

Textio is building a phone directory for its support team. Complete the addToPhonebook function. It takes a phoneNumber and name strings, and phoneBook map as inputs and returns a new map.