Plain objects as maps

A plain object is the oldest map in JavaScript: a name and a value, read with brackets or with a dot. It is the right tool for a record with known fields, and it is a poor one for a table whose keys come from data, for two reasons: every key is turned into a string, and every object already has keys it never asked for, inherited from its prototype.

This lesson looks at those inherited keys, at the two ways to ask whether a key is really there, at Object.create(null), which makes an object without a prototype, and at the cases where the object is still the better choice than the Map of the previous lessons.

Keys you did not set

Every object literal has a prototype, and the prototype has properties of its own: toString, constructor, hasOwnProperty and others. A lookup reads them as it reads the object, so a key that was never set can still answer with a function. The program prints a few of them.

const scores = {}; scores.ada = 36; console.log('a key that was set:', scores.ada); console.log('a key that was not:', scores.grace); console.log('but this one is there:', typeof scores.toString); console.log('and this one too:', typeof scores.constructor); console.log('own keys:', Object.keys(scores).join(',')); scores.constructor = 'a score'; console.log('a key from the prototype is now a value:', scores.constructor);

node prototype.js

a key that was set: 36
a key that was not: undefined
but this one is there: function
and this one too: function
own keys: ada
a key from the prototype is now a value: a score

The object has one own key and several inherited ones, and a lookup does not tell them apart: reading scores.toString gives a function that came from the prototype, not a value that was stored. The last line shows that a write does tell them apart, because it created an own key that now hides the inherited one. A table built from user input can therefore be made to answer with a function, which is the bug this section is about.

in and Object.hasOwn

in answers whether a key is anywhere in the chain, own or inherited, and Object.hasOwn answers whether the object holds it itself. The second is the question a map means, and the program asks both about a key that was set and one that comes from the prototype.

const flags = { dark: true }; console.log('the in operator with dark:', 'dark' in flags); console.log('the in operator with toString:', 'toString' in flags); console.log('own keys only:', Object.hasOwn(flags, 'dark'), Object.hasOwn(flags, 'toString')); console.log('values:', Object.keys(flags).join(','), JSON.stringify(Object.values(flags))); const report = Object.entries(flags).map(([key, value]) => `${key}=${value}`); console.log('entries:', report.join(','));

node own.js

the in operator with dark: true
the in operator with toString: true
own keys only: true false
values: dark [true]
entries: dark=true

The two in answers are both true, which is not what a caller of a map wants to hear about toString. Object.hasOwn gives the useful pair, and the list of keys and values contains only what the program put there. The entries call is the same answer in the shape of pairs, which is also what new Map(Object.entries(flags)) takes when the data has to become a Map.

Object.create(null)

Object.create(null) makes an object with no prototype at all, so it inherits nothing and a lookup finds only what was set. It is the object to use for a table whose keys come from outside the program. The program sets two keys and asks for an inherited name, and then copies the object with the spread syntax, which builds a normal object again.

const table = Object.create(null); table.ada = 36; table.grace = 40; console.log('a value:', table.ada); console.log('toString is not there:', typeof table.toString); console.log('own keys:', Object.keys(table).join(',')); console.log('JSON:', JSON.stringify(table)); const copy = { ...table }; console.log('a spread copy has a prototype again:', typeof copy.toString); console.log('the values came across:', JSON.stringify(copy));

node nullproto.js

a value: 36
toString is not there: undefined
own keys: ada,grace
JSON: {"ada":36,"grace":40}
a spread copy has a prototype again: function
the values came across: {"ada":36,"grace":40}

The table answered for the two keys it has and nothing for toString, which is the guarantee the literal does not give. JSON and Object.keys work as they do on any object, because both look at own enumerable keys only. The last two lines are the trap of the shortcut: the spread copies the keys and not the missing prototype, so a copy made that way is a normal object and every lookup has to use Object.hasOwn again.

When an object is the right map

An object is made of string keys it owns, and a Map is made of keys of any type in their insertion order. The difference that shows in output is the order: the keys of an object that look like array indexes come first, in ascending numeric order, and the rest follow in insertion order. The program puts that next to a Map on the same data, and shows the string conversion of keys.

const counts = Object.create(null); for (const word of ['a', 'b', 'a']) { counts[word] = (counts[word] ?? 0) + 1; } console.log('counts:', JSON.stringify(counts)); const numeric = { 10: 'ten', 2: 'two', 1: 'one' }; console.log('integer-like keys come first:', Object.keys(numeric).join(',')); const map = new Map([ [10, 'ten'], [2, 'two'], [1, 'one'], ]); console.log('a Map keeps the insertion order:', [...map.keys()].join(',')); const mixed = { 1: 'number key' }; mixed['1'] = 'text key'; console.log('1 and "1" are one key:', Object.keys(mixed).length, mixed[1]);

node when.js

counts: {"a":2,"b":1}
integer-like keys come first: 1,2,10
a Map keeps the insertion order: 10,2,1
1 and "1" are one key: 1 text key

Counting words in a table with no prototype is the case an object handles well: the keys arrive as text, the output is JSON, and the order of the words follows their first appearance. The two middle lines are the difference to remember: the object sorted its three keys as numbers while the Map kept the order in which they were given, so an object is not a good place for keys that have an order of their own. The last line is the string conversion in one example: the number 1 and the text "1" are the same key, and the second write replaced the first.

Exercises

  1. Read scores.hasOwnProperty from prototype.js. What type does it have, and which method gives the same answer without going through the prototype?
  2. Ask Object.hasOwn(flags, "valueOf") in own.js. Which of the two questions does it answer?
  3. Build the table in nullproto.js with a literal and look up toString. What comes back, and why?
  4. Add the key 7 to the numeric object in when.js. Where does it appear in the list of keys?
  5. Store the count of the word constructor in a literal table and then in Object.create(null). Which of the two gives a number back?

Questions

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

  1. Why can a lookup on a plain object find a key that was never set?

    Answer

    Because the object inherits keys from its prototype

    The prototype chain is part of every lookup, which is why toString and constructor answer on an empty object.

  2. Which call answers whether an object holds a key itself?

    Answer

    Object.hasOwn(object, "key")

    in reads the whole chain, and a stored undefined defeats the comparison with undefined.

  3. What does Object.create(null) make?

    Answer

    An object with no prototype and no inherited keys

    The null prototype is what removes the inherited keys from every lookup.

  4. What does this program print? const o = Object.create(null); o.a = 1; console.log(typeof o.toString, Object.keys(o).length);

    Answer

    undefined 1

    Nothing is inherited from a null prototype, and the one key that was set is the only one.

  5. What does this program print? const o = { 10: "a", 2: "b" }; console.log(Object.keys(o).join(","));

    Answer

    2,10

    Keys that look like array indexes come first in ascending numeric order, whatever the order of the literal.

  6. What does this program print? const o = {}; o[1] = "a"; o["1"] = "b"; console.log(Object.keys(o).length, o[1]);

    Answer

    1 b

    The number key becomes the text key, so the second write replaces the first value.

  7. What does this program print? const o = { a: 1 }; console.log("a" in o, Object.hasOwn(o, "a"));

    Answer

    true true

    The key is an own key, so both questions are answered with true.

  8. What does a spread copy of an object with a null prototype have?

    Answer

    The same keys and the normal object prototype

    The spread builds an object literal, and a literal has the usual prototype.

  9. When is a Map a better choice than a plain object?

    Answer

    When the keys come from data and may be objects, functions or numbers in a meaningful order

    A Map keeps any key type and the insertion order and has no inherited keys, while an object turns every key into a string.

  10. Which key can a Map hold that a plain object cannot?

    Answer

    An object used as a key

    A plain object turns every key into text, so two different objects become the same key, while a Map compares them by identity.

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