In JavaScript, a “dictionary” is typically an object or a Map. To add a key-value pair to an object, use obj[key] = value or Object.assign(); for a Map, use map.set(key, value). This article covers all the common methods, when to use each, and common pitfalls.
What Is a Dictionary in JavaScript?
JavaScript doesn’t have a built-in type called “dictionary” like Python or C#. Instead, developers use either plain objects ({}) or the Map class. Both store key-value pairs, but they behave differently in terms of key types, iteration order, and performance. Understanding these differences helps you choose the right structure for your task.
Adding to a Plain Object
The simplest way to add a key-value pair to an object is with bracket notation or dot notation:
const dict = {};
dict['name'] = 'Alice';
dict.age = 30;
console.log(dict); // { name: 'Alice', age: 30 }
Bracket notation is required when the key is not a valid identifier (e.g., contains spaces or hyphens) or when the key is stored in a variable. Dot notation is cleaner for simple property names.
You can also add multiple pairs at once using Object.assign():
const dict = { a: 1 };
Object.assign(dict, { b: 2, c: 3 });
console.log(dict); // { a: 1, b: 2, c: 3 }
Or use the spread operator to create a new object:
const original = { x: 1 };
const updated = { ...original, y: 2 };
console.log(updated); // { x: 1, y: 2 }
Adding to a Map
If you need a dictionary with non-string keys or need to preserve insertion order, use a Map. The set() method adds or updates an entry:
const map = new Map();
map.set('name', 'Bob');
map.set(42, 'answer');
map.set({id: 1}, 'object key');
console.log(map.get('name')); // 'Bob'
You can also initialize a Map with an array of key-value pairs:
const map = new Map([
['key1', 'value1'],
['key2', 'value2']
]);
Unlike objects, Map keys are not converted to strings, so 1 and '1' are distinct keys.
How to Choose: Object vs. Map
Use a plain object when:
- Keys are simple strings or symbols.
- You need JSON serialization (JSON.stringify works directly on objects).
- You want a simple, lightweight structure.
Use a Map when:
- Keys are not strings (numbers, objects, functions).
- You need to iterate in insertion order (objects also preserve order for string keys, but not for integer-like keys).
- You frequently add/remove entries and need better performance for large datasets.
- You need to check the size with
map.sizeinstead of counting keys manually.
Common Problems and Misconceptions
One common mistake is using the length property on an object—it doesn’t exist. Use Object.keys(obj).length instead. Another pitfall is accidentally overwriting prototype properties. If you add a key named toString or hasOwnProperty to a plain object, it can break code that relies on those methods. Using a Map avoids this entirely because Map keys do not interfere with prototype properties.
Also, be aware that object keys are automatically converted to strings. For example:
const obj = {};
obj[1] = 'one';
obj['1'] = 'also one';
console.log(obj); // { '1': 'also one' }
This can cause unexpected behavior if you’re not careful.
Alternatives: Set and Other Structures
If you only need to store unique values (not key-value pairs), a Set is more appropriate. For more complex data structures, consider using arrays of objects or libraries like Lodash, but native options are usually sufficient. For immutable updates (e.g., in React state), you might use the spread operator or libraries like Immer.
Performance and Safety Considerations
When adding many entries, Map generally has better performance for frequent additions and deletions. However, for small dictionaries, objects are faster and more memory-efficient. Always be mindful of prototype pollution: avoid using keys like __proto__ in objects, as they can modify the prototype chain. Use Object.create(null) to create a truly empty object if you need to avoid all prototype properties.
For security, never trust user input as a key directly without sanitizing, especially when using objects as dictionaries in a browser environment.
Frequently Asked Questions
How do I add a key-value pair to an object if the key is a variable?
Use bracket notation with the variable: const key = 'foo'; obj[key] = 'bar';.
Can I add a key-value pair to an object using a function?
Yes, you can define a function that takes the object, key, and value, then sets it: function addKey(obj, key, value) { obj[key] = value; }.
How do I check if a key exists in a dictionary?
For objects, use 'key' in obj or obj.hasOwnProperty('key'). For Maps, use map.has(key).
What’s the difference between obj.key and obj['key']?
They are functionally identical for simple string keys, but bracket notation allows dynamic keys and keys with special characters.
How do I add multiple key-value pairs at once?
Use Object.assign() or the spread operator for objects, or pass an array of pairs to the Map constructor or use map.set() in a loop.
Why does my object have a __proto__ key and how do I avoid it?
If you set a key named __proto__, it changes the object’s prototype instead of adding a normal property. Use Object.create(null) to create a dictionary without any prototype, or use a Map.
Related
- How to Improve Aim on Mouse: 12 Proven Steps
- Call of Duty on Mac: Can You Play It?
- Tough Bosch Cordless Drill Drivers: What Holds Up
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Add a Shared Mailbox in Legacy Outlook for MacTo add a shared mailbox in legacy Outlook for Mac, open Tools > Accounts, select your Exchange account,…
- Extracting Numbers from Text in ExcelThe fastest way to extract numbers from text in Excel is to use the VALUE function combined with…
- Add Page Numbers in Microsoft Word: Step-by-StepTo add page numbers in Microsoft Word for Microsoft 365 on Windows, open the document, choose Insert >…
- How to Archive and Save Emails in Outlook SecurelyTo archive an email in Outlook, select it and choose Archive; Outlook moves it to the Archive folder…
- How to Change a Date Format to a Custom Format in ExcelTo change a date to a custom format in Excel for Microsoft 365 on Windows, select the date…
- Excel Regression Analysis: Run It and Read the ResultsExcel regression analysis estimates how one or more input variables relate to an outcome. In Microsoft Excel for…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.