DEV Community

hrishikesh1990
hrishikesh1990

Posted on • Originally published at flexiple.com

How to create a JavaScript Dictionary?

In this short tutorial, we look at all the methods you could use to create a JavaScript Dictionary. We also look at a few limitations and caveats.

If you are new to programming or JavaScript, we recommend you read through the entire article. However, If you are just looking for the code, you can skip to the code section below.

Table of Contents - JavaScript Dictionary

Are there dictionaries in JavaScript?

No, as of now JavaScript does not include a native “Dictionary” data type. However, Objects in JavaScript are quite flexible and can be used to create key-value pairs. These objects are quite similar to dictionaries and work alike.

Dictionaries are commonly used as each value stored has a unique key, and through these keys, their respective values can be accessed. This allows a lot of flexibility while reading and storing data.

Creating a JavaScript Dictionary

A dictionary can be created using two methods. The Object Literal method or by using the new keyword. However, we focus on the former. This is because it is very likely that you have used dictionaries before and this method follows a familiar syntax.

Syntax using Object literals:

To create an empty JavaScript dictionary.

var dict = {}
Enter fullscreen mode Exit fullscreen mode

Here “dict” is the name of the object.

Initializing and creating a dictionary:

var dict = {
  Name: "Eric",
  Age = 23
  Job: "Freelancer",
  Skills : "JavaScript"
};
Enter fullscreen mode Exit fullscreen mode

Adding, accessing & deleting values

Key-value pairs can be added while creating a JavaScript dictionary, however, these methods can also be used to add values.

The code to add items:

dict[key] = value
Enter fullscreen mode Exit fullscreen mode

Here “key” refers to the name of the unique key and “value” is the respective data the key references to.

In case the dictionary already contains the name you have passed as the key, you could either rename your key or you could use the following code to update the value.

dict.key = new_value; 
Enter fullscreen mode Exit fullscreen mode

Accessing items is also very straightforward; the following code can be used.

The code to access items:

var value = dict.key;
Enter fullscreen mode Exit fullscreen mode

Here “value” refers to the variable you are using to store the accessed key’s value.

Deleting items is also easy. We use the delete keyword to delete the item.
The code to delete items:
delete dict.key;

Limitation and Caveats - JavaScript Dictionary:

  • The new object method can also be used but keeping readability in mind, I have suggested the above method.
  • Be aware of your naming convention, I would recommend using a common style for all your keys. This would help access them easily.

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy 🎖️