How to Create a Dictionary in JavaScript

To create a Dictionary in JavaScript, you can use the “Object” or “Map” instance. In JavaScript, dictionaries are typically represented as Objects or Map.

Method 1: Using the Object

JavaScript Objects are a collection of key-value pairs, where keys are strings and values can be any data type. They are a simple and intuitive way to create dictionaries in JavaScript.

Object keys can be accessed using dot notation (e.g., object.key) or bracket notation (e.g., object[‘key’]). However, objects have a prototype, so they might have additional inherited properties, sometimes leading to unexpected behavior.

Objects do not guarantee any specific order for their property keys, and non-string keys are automatically converted to strings.

Example

const dictionary = {
  key1: 'value1',
  key2: 'value2',
  key3: 'value3'
};

console.log(dictionary.key1);
console.log(dictionary['key2']);

Output

value1
value2

Method 2: Using a Map

A Map is a built-in JavaScript data structure that holds “key-value” pairs and maintains the insertion order of its elements. It allows any value to be used as a key, including objects and functions.

Map instances provide several utility methods, such as get, set, has, delete, and iteration methods, which make it easier to work with key-value pairs.

Example

const dictionary = new Map([
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key3', 'value3']
]);

console.log(dictionary.get('key1'));
console.log(dictionary.get('key2'));

Output

value1
value2

For most use cases, a Map is recommended when you need a dictionary-like data structure in JavaScript.

Unlike Objects, Map instances do not have a prototype, so they only contain the keys explicitly added to them. However, using an Object may be more suitable if you need to work with JSON data or need a simple, lightweight data structure.

Leave a Comment