How to Create Dictionaries in JavaScript

How to Create Dictionaries in JavaScript

Taking a look at the object data type
Ferenc Almasi β€’ Last updated 2024 February 08 β€’ Read time 7 min read
Unlike in statically typed languages, there is no Dictionary type in JavaScript. Learn what are the alternative data types to achieve the same.
  • twitter
  • facebook
JavaScript

In programming languages, a common data structure called a dictionary is often used for storing data in key-value pairs. It provides a flexible way to store and read data when it's presented with a key. Unlike in statically typed languages, however, there is no such type as Dictionary in JavaScript. So how do we create one? We have a couple of options.


Creating a Dictionary in JavaScript

In JavaScript, dictionaries can be created through Objects. To create a new object (among many other options), we can use an object literal:

Copied to clipboard!
// Using object literals
const obj = {
    key: 'value'
}
Creating a dictionary (object) in JavaScript

Objects can be defined using curly braces. Each object can contain an arbitrary number of values, called properties. These properties are created using key-value pairs. If you’re interested in what are some other less commonly used ways to create objects, be sure to check out the following tutorial:

How to Create Objects in JavaScript?

How to Add Values to a Dictionary

To add values to a dictionary β€” a JavaScript object β€”, we can initialize it with key-value pairs as in the previous example:

Copied to clipboard! Playground
// Add default values during initialization
const dictionary = {
    PUBLIC_API_KEY: '1c6aa69fb9d27cb4f29c81611d0b1ff5',
    PRIVATE_API_KEY: '4fa758e6d388593f8637da4bdd697ef6'
}
How to add values to JavaScript objects

Moving forward, we'll refer to dictionaries as "objects".

In this example, our object will have two properties: PUBLIC_API_KEY and PRIVATE_API_KEY. We can name object keys however we like, as long as they only contain valid characters from the English alphabet. We can also use different naming conventions, such as snake_case in the above example. Most commonly, however, JavaScript uses camelCase. The values of keys can be any valid JavaScript data type, including other objects. Take the following as an example:

Copied to clipboard! Playground
const dictionary = {
    user: {
        name: 'John'
    }
}
Object containing an object in JavaScript

In this case, our dictionary variable has a user key that references another object, which has a name property. To populate our object with additional values after declaration, we can use indexes, bracket notation, or just call a property directly with dot notation:

🚫 Refresh console

If we try to log out the dictionary variable to the console, we'll get the above output. Note that with bracket notation, we can also use a dash. This is not the case for the other options. If we try to set it through dot notation, we'll get the following error:

Invalid left-hand side assignment when we try to use dash with dot notation
Invalid left-hand side assignment when we try to use dash with dot notation

We also have the option to use other variables as a name for keys in the object, using bracket notation. This makes it possible to dynamically set properties. Simply pass the variable between brackets:

Copied to clipboard! Playground
const key = 'blue-book'
const dictionary = {
    [key]: 'πŸ“˜'
};

// You can also do
dictionary[key] = 'πŸ“˜'
Note that bracket notations inside objects are only available in ES6 and above

Try to copy-paste the above code into the interactive editor and log out the value of the dictionary variable to verify its properties.

Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScriptinfo Remove ads

How to Access Keys

If we want to access these values, we can use the same options as before, just without the assignment:

Copied to clipboard! Playground
// Returns "c8b0c9e9b1618b4fb35c47ed4e2fadc7"
dictionary[2]

// Returns "πŸ“˜"
dictionary['blue-book']

// Returns "πŸ“’"
dictionary.book
How to access object keys in JavaScript

Note that if we want to access a property that has a dash or number in it, we have to use bracket notation again. Accessing properties with variables is also possible, just like creating new ones:

Copied to clipboard!
const key = 'blue-book'

// Returns "πŸ“˜"
dictionary[key]
Accessing object properties through variables

When working with nested objects, the most common way to access the value is to use dot notation in the following way:

🚫 Refresh console

However, as we can see, we can also use bracket notation by combining multiple brackets after each other. In this case, we need to pass the keys as strings inside the brackets.

Note that in case one of the properties is undefined, we'll run into an error. To get around this, we have several options that are outside the scope of this tutorial. However, if you're interested in how to resolve them, be sure to check out the following tutorial that discusses the possible options in detail:

How to Check If A Key Exists In An Object In JavaScript

Iterating Through Dictionaries

If we want to loop through our whole object, we can use a for...in loop in the following way:

🚫 Refresh console

To filter out inherited properties, we can use an if statement to check whether the property we are working on belongs to the dictionary. Note that we can access values inside the loop with bracket notation. We can also use a more declarative approach using Object.entries combined with a forEach loop:

Copied to clipboard!
Object.entries(dictionary).forEach(entry => {
    console.log(`key: ${entry[0]}, value: ${entry[1]}`)
})
How to loop through an object in JavaScript

Try replacing the for loop in the interactive editor to verify that the output of the above code matches the output of the for loop. Object.entries turn the object into an array of elements, each array containing a subarray that contains the key and the value. Try logging out only the value of Object.entries to see its return value. You can reveal the solution on how to achieve this if you get stuck.

Copied to clipboard!
console.log(Object.entries(dictionary))

As Object.entries return an array, we can chain the forEach array method to loop through the elements and log the values to the console. This is called function chaining.


Dictionaries with Maps

Another data type in JavaScript that is similar to objects but comes with added benefits is maps. Just like objects, they hold key-value pairs, but they remember the insertion order of the keys, and they also come with helper methods. To create a new map, we can use the following code:

🚫 Refresh console

We initialize the dictionary variable to an empty map. To add values to a map, we can use the set method that accepts two parameters: key and value. To reference these values later on, we need to use the get method. Try to log the name property of the map in the above editor. Make sure to pass the key as a string to the get method.

Copied to clipboard!
console.log(dictionary.get('name'))

Apart from set and get, maps also have the following helper methods to make working with them easier:

Copied to clipboard!
dictionary.has('name')
dictionary.size
dictionary.delete('age')
dictionary.clear()
How to operate on maps in JavaScript
  • has: We can use has to check if the map has the passed key. It'll return true if the key exists and false if not.
  • size: Returns the number of key-value pairs in the map. In our example, it'll return two, as we have a name and age keys.
  • delete: Deletes the passed key from the map. If the key exists, it'll return true. Otherwise, it'll return false. If we call has on a deleted key, it'll return false.
  • clear: Remove all key-value pairs from the map, leaving an empty map.

Maps also come with different methods that can be used for looping through them:

Copied to clipboard! Playground
// Loop through keys and values:
for (const [key, value] of dictionary.entries()) {
    console.log(key, value)
}

// Loop through keys only:
for (const key of dictionary.keys()) {
    console.log(key)
}

// Loop through values only:
for (const value of dictionary.values()) {
    console.log(value)
}
How to iterate through JavaScript maps

We can use the entries method to loop on both keys and values, use the keys method to loop only on keys or use the values method to loop only on values.


Things to Keep in Mind

And that is how you can create dictionaries in JavaScript. Some things to keep in mind:

  • Use object literals for better readability when creating new objects.
  • Try to stick to one naming convention whether it be camelCase, snake_case, or kebab-case.
  • You can use variables to write and access properties.
  • Make sure to include an if statement inside a for...in loop if you want to filter out inherited properties. However, prefer using Object.entries for improved readability.
  • Only use maps over objects when you need to frequently modify a collection. Using the set and delete methods of maps can improve code readability and have better performance over regular objects:
🚫 Refresh console

Do you still have questions regarding objects in JavaScript? Let us know in the comments below so we can help! Thank you for reading through, happy coding! To learn more about JavaScript, continue with our guided roadmap:

JavaScript Roadmap
  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.