JavaScript Dictionary: The Best Ways to Create One

Download Now: Free Website Optimization Checklist
Athena Ozanich
Athena Ozanich

Updated:

Published:

Ever thought of the redundancy of defining a dictionary? It’s a humorous idea, like using a forklift to lift a forklift; it’s as redundant as it is recursive. But I must digress because, in this post, we are not talking about silly programming humor; we’ll save that for another time.

Woman studying data structures and JavaScript dictionaries.

Instead, we will discuss creating a JavaScript dictionary or creating something very similar. Unfortunately, JavaScript does not yet have a dictionary type, so we’ll have to use the awesome powers offered by objects and ES6 maps.

For a brief overview of the very basics of JavaScript check out our other post — insert shameless self plug — here.

Without further ado, let’s dive in.

Free Resource: Website Optimization Checklist [Download Now]

Create a Dictionary With JavaScript

To create a dictionary with JavaScript, we will need to use JavaScript Objects and store our data as key and value pairs. This process is relatively simple and takes only a few minutes to accomplish.

JavaScript offers more than just the ability to store data in this fashion; it also allows us to iterate over and access the data. To create this dictionary, we will start by declaring a new dictionary object; let’s look at this.

const person = { firstName: "John", lastName: "Doe", age: 50, status: "marketing contact" };

We start by creating a variable for the object — which we named person — and then assign keys and values to that object. The keys in this object are firstName, lastName, and so on, while the values are John, Doe, etc. Furthermore, this is not the only way to create an object with key/value pairs. Another way we can do this is by explicitly declaring the object using the new keyword.

const person = new Object()

To create an object that does not include the default methods that come with the object prototype, we can take a slightly different approach; let’s look at that next.

const person = Object.create(null)

And, to populate this object with data, we can use bracket notation to assign keys and values to our new object.

person[firstName] = "John"

Next, let’s take a closer look at object keys and how they work.

Featured Resource

An Introduction to JavaScript Guide

Fill out the form to get your free guide.

 

Featured Resource

An Introduction to JavaScript Guide

Fill out the form to get your free guide.

 

JavaScript Dictionary Keys

With JavaScript, we can assign different data types to our objects, such as strings, integers, and even methods — functions tied to an object — giving us powerful objects.

const method = () => console.log("Hello"); const person = { mood: "happy", 1: [12, 14, 90], 1.2: 123, MyMethod: method };

Object keys can only be strings, and even though a developer can use other data types to set keys, JavaScript will convert them to a string value. As shown below, we can also access our keys via either the dot notation or the bracket notation.

const person = { firstName: "John", lastName: "Doe", age: 50, status: "marketing contact" }; person["firstName"]; /*returns the value John"*/ person.firstName; /*Also returns the value "John"*/

Iterate Through JavaScript Dictionary Object

Checking the length of our dictionary — the number of keys — is a helpful tool for working with our object. The most efficient way to check the size with a traditional object is to iterate through and count the number of keys found using a for loop.

for (const key of Object.keys(person)) { console.log(key + ":" + person[key]); }

With this said, I’d be remiss if I didn’t explain that there is a better way to create and interact with a dictionary. This other method is where we get to see the power of ES6 Maps; they offer valuable methods and improved reliability for such use.

JavaScript Maps

Maps are handy and provide benefits that standard objects do not; let’s look at those next.

  • Keys in maps can be of any type and are not converted to strings like they are with an object.
  • A Map orders its key-value pairs in the order they are added; however, this is not as reliable and straightforward with an Object.
  • Maps have a size property that directly retrieves the number of stored key-value pairs. With Objects, we have to manually calculate the size using loops and Object.keys — or similar methods.

Creating Maps with JavaScript is very easy and isn’t much different from the syntax for objects. Let’s look at what that looks like below.

/*Create Map instance*/ let person = new Map();

Add to JavaScript Dictionary

Adding new keys to our dictionary is very simple with Maps; we can use the set method to set new keys and values explicitly.

/*Add key-value pairs*/ person.set("id", 123); person.set("registered", true); let name = { firstName: "Anj" }; /*Add keys of different types*/ /*Creates an integer key = (1) with an array value = ([1, 2, 3, 5])*/ person.set(1, [1, 2, 3, 5]); /*Creates a object key = (name) with a string value = ("available")*/ person.set(name, "available");

We have four keys for our person map in the above example, each with different data types. This method allows for more flexibility and control in our dictionary.

Check if key/value exists in JavaScript Dictionary.

Likewise, we can check if an object has a specific key within it using the provided method has; let’s look at that next.

person.has("dog"); /*false*/ person.has("id"); /*true*/

Remove key/value pair from the JavaScript Dictionary.

We can make removals and deletions to our dictionary using another method provided by Maps called delete. Let’s take a quick look at what that looks like below.

person.delete(name); /*true*/

Check the size of the JavaScript Dictionary.

Using Maps, we can quickly check the size of our dictionary by using a method provided with Maps called size.

person.size /*returns the number of keys*/

Iterate Through JavaScript Dictionary Map

Maps also provide separate entries(), keys(), and values() functions to iterate over keys and values in different ways depending on the use case.

/*Best for accessing both keys and their values*/ for (const [key, value] of person.entries()) { console.log(key + ": " + value); } /*Best for accessing only the keys*/ for (const key of person.keys()) { console.log(key); } /*Best for accessing only the values*/ for (const value of person.values()) { console.log(value); }

Takeaways for Creating a JavaScript Dictionary

While JavaScript does not have a native dictionary type, it does offer more than one way to create a dictionary-like data structure. Between the use of objects and Maps, creating a dictionary of varying data types becomes very easy to accomplish.

Deciding which of these approaches will suit your needs best depends on the data you are storing and its complexity. For example, if you only keep static strings as keys, then an object may work best as it will run faster due to its simplicity. However, if you are storing keys with other data types, you will want to use Maps, considering that maps are a little more processing intensive.

Armed with the information above, hopefully you feel more confident in building your Javascript dictionaries.

New Call-to-action

Topics: Javascript

Related Articles

Access a free checklist to maximize your website's performance, SEO, and security.

    CMS Hub is flexible for marketers, powerful for developers, and gives customers a personalized, secure experience

    START FREE OR GET A DEMO