Map: keys of any type

A Map stores a value under a key and keeps the two together: the key can be any value, including an object or a function, and it is compared by identity rather than by text. JavaScript objects look like maps and are not, because every key of an object is turned into a string and every object starts with a set of keys inherited from its prototype.

This lesson covers the five methods that do the work, the keys that a plain object cannot hold, the insertion order that makes the output of a program predictable, and the four ways to walk a map. The lesson on plain objects as maps takes the other side of the comparison.

set, get, has and delete

set stores a value under a key and returns the map, so calls can be chained; get returns the value or undefined; has answers whether a key is there; delete removes one and reports whether it was found; and size is the number of entries.

const scores = new Map(); scores.set('ada', 36); scores.set('alan', 41); console.log('size:', scores.size); console.log('get ada:', scores.get('ada')); console.log('get a missing key:', scores.get('grace')); console.log('has alan:', scores.has('alan')); console.log('set returns the map:', scores.set('grace', 40) === scores); console.log('size after the chain:', scores.size); console.log('delete:', scores.delete('alan'), scores.delete('alan')); console.log('size now:', scores.size); console.log('as pairs:', JSON.stringify([...scores]));

node basics.js

size: 2
get ada: 36
get a missing key: undefined
has alan: true
set returns the map: true
size after the chain: 3
delete: true false
size now: 2
as pairs: [["ada",36],["grace",40]]

Four calls in three lines: set added a third entry and returned the map, delete removed one and then reported that there was nothing left to remove. The missing key gave undefined and no error, which is why has exists: a stored undefined and a key that is not there look the same through get. The last line spreads the map into pairs, which is the shape JSON can hold.

Keys of any type

A key of a Map can be an object, a function, a number or a boolean, and the map compares keys with the rule that two objects are equal only when they are the same object. That makes a Map the right place for data about a record without adding a field to it. A plain object with an object as a key does something else entirely: it converts the key to a string.

const ada = { name: 'ada' }; const alan = { name: 'alan' }; const scores = new Map(); scores.set(ada, 36); scores.set(alan, 41); console.log('by the object itself:', scores.get(ada)); console.log('a look-alike key:', scores.get({ name: 'ada' })); console.log('keys are compared by identity:', scores.has(ada), scores.has({ name: 'ada' })); const key = () => 'x'; scores.set(key, 'a function'); console.log('a function key:', scores.get(key)); console.log('the same code is another key:', scores.get(() => 'x')); const asObject = {}; asObject[ada] = 36; asObject[alan] = 41; console.log('a plain object has one key:', Object.keys(asObject).join(',')); console.log('and one value:', JSON.stringify(Object.values(asObject)));

node objectkeys.js

by the object itself: 36
a look-alike key: undefined
keys are compared by identity: true false
a function key: a function
the same code is another key: undefined
a plain object has one key: [object Object]
and one value: [41]

The look-alike key found nothing, because the map compares the reference and not the fields and a fresh object is always another reference. A function works as a key in the same way, and a second function with the same body is a different key again. The last two lines are the failure of the object version: both objects became the text [object Object], one key was written twice, and the first value was replaced by the second.

Insertion order

A Map keeps its entries in the order in which the keys were first inserted, and updating a key does not move it. A key that is deleted and then set again is a new insertion and goes to the end. The program shows both cases through the list of keys.

const map = new Map([ ['first', 1], ['second', 2], ['third', 3], ]); map.set('first', 10); console.log('an update keeps the position:', [...map.keys()].join(',')); console.log('values:', [...map.values()].join(',')); map.delete('second'); map.set('second', 20); console.log('a delete and a set move it to the end:', [...map.keys()].join(',')); console.log('size:', map.size);

node order.js

an update keeps the position: first,second,third
values: 10,2,3
a delete and a set move it to the end: first,third,second
size: 3

The keys were in the order of the constructor call, and the update of first changed the value to 10 while the key stayed first. The delete took second out of the order and the set after it put the key back at the end. This order is guaranteed by the language, so a map can be serialised and read back in the same order, and a program can print its entries without sorting them for the output to be stable.

Walking a Map

A Map is iterable and yields a pair for each entry, so for...of with a destructuring pattern reads the key and the value. keys, values and entries give the three views as iterators, and the spread turns any of them into an array. A Map is built from an array of pairs or from the entries of an object.

const counts = new Map([ ['a', 2], ['b', 1], ]); for (const [key, value] of counts) { console.log(`${key}: ${value}`); } const doubled = new Map([...counts].map(([key, value]) => [key, value * 2])); console.log('built from entries:', JSON.stringify([...doubled])); console.log('from an object:', JSON.stringify([...new Map(Object.entries({ x: 1, y: 2 }))])); console.log('the property form does not read a Map:', counts.a);

node iterate.js

a: 2
b: 1
built from entries: [["a",4],["b",2]]
from an object: [["x",1],["y",2]]
the property form does not read a Map: undefined

The loop destructured each pair, which works because the default iterator of a Map yields [key, value] arrays. The new map was built from pairs with a map over the entries, and the object gave its own entries to the constructor. The last line is the habit to drop: counts.a reads a property of the map object and not an entry, and it is undefined even when the key exists, which is why the methods and not the brackets are the way in.

Exercises

  1. Store undefined under a key in basics.js and read it back twice, once with get and once with has. Which of the two tells the key apart from a missing one?
  2. Use the same object twice as a key, first with one value and then with another. How many entries does the map have?
  3. Build a map from an array of three pairs and delete the middle key. What does [...map.keys()] show afterwards?
  4. Turn the doubled map in iterate.js back into a plain object with Object.fromEntries. What does the result print?
  5. Add a fourth entry to the map in order.js and print the keys. Where does the new key appear?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does map.get return for a key that is not there?

    Answer

    undefined

    A lookup without a match gives undefined, and has is the method that tells it from a stored undefined.

  2. What does map.set(key, value) return?

    Answer

    The map itself

    It returns the map, which is what makes chained set calls possible.

  3. What can be a key of a Map?

    Answer

    Any value, including an object or a function

    A Map compares keys by identity, so any value can be one.

  4. What does this program print? const a = { id: 1 }; const m = new Map([[a, "x"]]); console.log(m.get({ id: 1 }));

    Answer

    undefined

    The key in the map is the object a, and the look-alike in the call is another object.

  5. What does this program print? const o = {}; const a = { id: 1 }; const b = { id: 2 }; o[a] = 1; o[b] = 2; console.log(Object.keys(o).length);

    Answer

    1

    Both objects are converted to the same string, so the second write replaces the first.

  6. What does this program print? const m = new Map([["a", 1], ["b", 2]]); m.set("a", 3); console.log([...m.keys()].join(","));

    Answer

    a,b

    An update of an existing key keeps its position, so the order of the keys does not change.

  7. What does [...new Map([["a", 1]])] give?

    Answer

    [["a", 1]]

    The iterator of a Map yields a pair per entry, so the spread gives an array of pairs.

  8. How does a loop read the key and the value of each entry?

    Answer

    With a destructuring pattern: for (const [key, value] of map)

    Each step of the iterator is an array of two items, which the pattern takes apart.

  9. What does this program print? const m = new Map([["a", 1]]); m.delete("a"); m.set("a", 2); console.log([...m.values()].join(","));

    Answer

    2

    The delete removed the entry and the set made a new one, so the map holds one value.

  10. Why is JSON.stringify([...map]) a better way to print a Map than console.log(map)?

    Answer

    The spread gives the entry pairs, which JSON writes as a value of the program

    The console view of a collection is a convenience of the runtime and differs between versions, while a string built from the pairs is decided by the program.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev