Dictionary in JavaScript

Introduction to Dictionaries in JavaScript

JavaScript is a versatile programming language widely employed in web development. A dictionary, often referred to as an object, represents one of the fundamental data structures in this language. Dictionaries are primarily used for the storage and manipulation of collections consisting of key-value pairs. In this article, we will explore the creation of word references, known as dictionaries, in JavaScript. We will also discuss how to interact with them and their common applications, while providing a thoroughly commented code example for clarity.

What is a Dictionary?

In JavaScript, a dictionary is a specific kind of object that organizes data in pairs of keys and values. The keys, known as identifiers, allow for rapid and direct access to the data you need. Dictionaries are particularly effective for linking unique IDs with their relevant values, making them ideal for situations where it's necessary to save user details, including configuration options or any other information that requires access via keys.

Creating a Dictionary

Creating a dictionary in JavaScript is an uncomplicated task. You have the option to utilize either object literals or the Object constructor.

1. Using Object Literals

Object literals provide a succinct way to create dictionaries.

Example

// Creating a dictionary using object literals
const dictionary = {
  key1: "value1",  // key1 is associated with the string "value1"
  key2: "value2",  // key2 is associated with the string "value2"
  key3: "value3"   // key3 is associated with the string "value3"
};

console.log(dictionary);  // Output the entire dictionary to the console

Output:

Output

{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}

2. Using the Object Constructor

The Object constructor remains a viable option for creating dictionaries; however, its prevalence in usage is significantly less than that of object literals.

Example

// Creating a dictionary using the Object constructor
const dictionary = new Object();  // Create a new, empty dictionary

dictionary.key1 = "value1";  // Assign "value1" to key1
dictionary.key2 = "value2";  // Assign "value2" to key2
dictionary.key3 = "value3";  // Assign "value3" to key3

console.log(dictionary);  // Output the entire dictionary to the console

Output:

Output

{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}

Accessing and Modifying Dictionary Elements

After you have established a dictionary, you can move on to accessing and altering its elements through either dot notation or bracket notation as different options.

1. Dot Notation

Dots serve as the exclusive characters in a dot notation expression that exclusively navigate through them, rendering them straightforward and easy to comprehend.

Example

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

console.log(dictionary.key1);  // Access the value associated with key1
dictionary.key2 = "newValue2";  // Modify the value associated with key2
console.log(dictionary.key2);  // Output the modified value of key2

Output:

Output

value1
newValue2

2. Bracket Notation

Bracket notation proves to be useful when a property name does not conform to the standards of a valid JavaScript identifier or when the property name is derived from a JavaScript expression. In these instances, it is necessary to utilize bracket notation exclusively. This is a scenario where JavaScript relaxes its syntax rules, opting for a more adaptable syntax referred to as bracket notation.

Example

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

console.log(dictionary["key1"]);  // Access the value associated with key1 using bracket notation
dictionary["key2"] = "newValue2";  // Modify the value associated with key2 using bracket notation
console.log(dictionary["key2"]);  // Output the modified value of key2

Output:

Output

value1
newValue2

Adding and Deleting Dictionary Elements

A dictionary object is a data structure that holds pairs of keys and values. You can effortlessly introduce new pairs or eliminate existing ones by utilizing the delete statement followed by a space and the specified key name.

1. Adding Elements

However, adding new keys and their corresponding values to an already established dictionary can be accomplished by substituting a new key with its associated value.

Example

const dictionary = {
  key1: "value1",
  key2: "value2"
};

dictionary.key3 = "value3";  // Add a new key-value pair
dictionary["key4"] = "value4";  // Add another new key-value pair using bracket notation

console.log(dictionary);  // Output the updated dictionary

Output:

Output

{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3",
  "key4": "value4"
}

2. Deleting Elements

It is advisable to utilize the delete operator for this purpose, as the proper technique for eliminating an item from a dictionary involves employing the delete keyword.

Example

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

delete dictionary.key2;  // Delete the key-value pair associated with key2
delete dictionary["key3"];  // Delete the key-value pair associated with key3 using bracket notation

console.log(dictionary);  // Output the updated dictionary

Output:

Output

{
  "key1": "value1"
}

Checking for Key Existence

Numerous developers regard verifying the existence of a key within an object as a frequent scenario. You have the option to employ the built-in operator or alternatively, use a method such as hasOwnProperty to perform this check manually.

1. Using the in Operator

The in operator serves as a member function that checks for the presence of a key within a dictionary.

Example

const dictionary = {
  key1: "value1",
  key2: "value2"
};

console.log("key1" in dictionary);  // Check if key1 exists in the dictionary
console.log("key3" in dictionary);  // Check if key3 exists in the dictionary

Output:

Output

true
false

2. Using the hasOwnProperty Method

The hasOwnProperty function returns true if the specified key exists as a direct property of the dictionary object.

Example

const dictionary = {
  key1: "value1",
  key2: "value2"
};

console.log(dictionary.hasOwnProperty("key1"));  // Check if the dictionary has key1
console.log(dictionary.hasOwnProperty("key3"));  // Check if the dictionary has key3

Output:

Output

true
false

Iterating Over a Dictionary

A method to traverse all the keys along with their corresponding values in a dictionary involves utilizing for...in, Object.keys, Object.values, and Object.entries.

1. Use for...in

The for...in construct offers a method to loop through all enumerable properties of an object, including both its own properties and the built-in ones.

Example

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

for (let key in dictionary) {  // Iterate over all keys in the dictionary
  console.log(key, dictionary[key]);  // Output each key and its associated value
}

Output:

Output

key1 value1
key2 value2
key3 value3

2. Using Object.keys

The Object.keys function returns an array that contains the keys of a given object.

Example

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

Object.keys(dictionary).forEach(key => {  // Iterate over the array of keys
  console.log(key, dictionary[key]);  // Output each key and its associated value
});

Output:

Output

key1 value1
key2 value2
key3 value3

3. Using Object.values

The Object.values function retrieves an array that contains the values from an object.

Example

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

Object.values(dictionary).forEach(value => {  // Iterate over the array of values
  console.log(value);  // Output each value
});

Output:

Output

value1
value2
value3

4. Using Object.entries

A method to achieve this is by utilizing the Object.entries function, which produces an array comprised of sub-arrays containing keys and their corresponding values.

Example

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

Object.entries(dictionary).forEach(([key, value]) => {  // Iterate over the array of key-value pairs
  console.log(key, value);  // Output each key and its associated value
});

Output:

Output

key1 value1
key2 value2
key3 value3

Practical Use Cases

1. Storing User Information

User dictionaries serve as an excellent means for storing user attributes, with each key representing a specific user attribute.

Example

const user = {
  name: "John",  // User's name
  email: "john.usa@example.com",  // User's email
  age: 30,  // User's age
  isAdmin: false  // Whether the uaser is an admin
};

console.log(user.name);  // Output the user's name
console.log(user.email);  // Output the user's email

Output:

Output

John 
john.usa@example.com

2. Configuration Settings

The dictionary is ideal for storing configuration settings for applications.

Example

const config = {
  apiEndpoint: "https://api.logic-practice.com",  // API endpoint URL
  timeout: 5000,  // Timeout duration in milliseconds
  debugMode: true  // Whether debug mode is enabled
};

console.log(config.apiEndpoint);  // Output the API endpoint URL
console.log(config.timeout);  // Output the timeout duration

Output:

Output

https://api.logic-practice.com
5000

3. Caching Data

Dictionaries offer substantial accessibility when certain data is omitted, allowing for improved performance and efficiency.

Example

const cache = {};  // Initialize an empty cache

function fetchData(key) {
  if (key in cache) {  // Check if the data is already cached
    return cache[key];  // Return the cached data
  } else {
    // Simulate fetching data from a database or API
    const data = `Data for ${key}`;  // Simulated data
    cache[key] = data;  // Cache the fetched data
    return data;  // Return the fetched data
  }
}

console.log(fetchData("item1"));  // Fetch data for item1 and cache it
console.log(fetchData("item1"));  // Retrieve the cached data for item1

Output:

Output

Data for item1
Data for item1

Conclusion

In JavaScript, dictionaries function similarly to arrays that are utilized for the storage of comparable data. However, they are generally employed for more intricate, real-world information that would be unwieldy and inefficient to manage.

This article will guide you through the process of creating, altering, and executing iterators in the most straightforward manner by utilizing a dictionary. We have examined practical examples to provide you with a clear understanding of their application. The perspective of a dictionary should be tailored to instruct learners on how to craft more efficient and resilient code using JavaScript.

Input Required

This code uses input(). Please provide values below: