Technical skill practice

Dictionary in JavaScript: Choose Object Keys or Map Keys

JavaScript can represent a dictionary with an object or a Map. Choose from the key contract: object property keys and Map keys do not treat every input in the same way.

The task

Store desk labels under textual keys in an object, then compare numeric 7 and string “7” as keys in both structures. Use a null-prototype object for the explicit property-key dictionary.

Runnable Node 22 example

const assert = require('node:assert/strict');

const desks = Object.create(null);
desks.north = 'A2';
desks[7] = 'numeric entry';
desks['7'] = 'text entry';
assert.equal(desks[7], 'text entry');
const lookup = new Map([[7, 'numeric entry'], ['7', 'text entry']]);
assert.equal(lookup.size, 2);
assert.equal(lookup.get(7), 'numeric entry');
assert.equal(lookup.get('7'), 'text entry');
assert.equal(desks.north, 'A2');
console.log(`object=${desks[7]}; map=${lookup.get(7)}; entries=${lookup.size}`);

Expected output and explanation

The object assignments address the same property key, so the later text entry replaces the earlier value. The Map retains separate numeric and string keys and reports two entries. That difference can determine whether a lookup silently overwrites a value.

The null-prototype object avoids an inherited Object.prototype for this small dictionary, but it still has property-key semantics. Map offers entry operations such as get and has rather than ordinary property access for stored entries. Choose consistently rather than writing lookup[key] and expecting a Map entry.

Output from the example

object=text entry; map=numeric entry; entries=2

Pitfall to check

If keys come from external input, define their type and permitted range before storing them. A null-prototype object is not permission to assign arbitrary configuration fields into some other object.

Questions, answered

Can a Map use objects as keys?

Yes, with identity-based matching. A newly created equal-looking object is a different key unless you define another indexing policy.

Sources and examples

ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.

Your experience. A complete resume.

Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.

Free account required. Free-plan PDF exports include a watermark.