JavaScript Basics: How to Create and Use a Dictionary
As a beginner in JavaScript, learning how to create and use a dictionary can be a useful tool in many web development projects. A dictionary is simply an object that allows you to store and access key-value pairs of data. In this article, we will be covering how to create and use a dictionary in JavaScript, and the basic methods you can use to manipulate its data.
Creating a Dictionary
To create a dictionary in JavaScript, you can simply define an empty object literal with curly braces:
“`
let dictionary = {};
“`
You can also define a dictionary with some initial key-value pairs:
“`
let dictionary = {
“key1”: “value1”,
“key2”: “value2”
};
“`
In this example, we have created a dictionary with two key-value pairs, where “key1” and “key2” are the keys, and
“value1” and “value2” are the corresponding values.
Accessing Dictionary Values
To access a value in a dictionary, you can use the square bracket notation and pass in the key:
“`
let dictionary = {
“key1”: “value1”,
“key2”: “value2”
};
console.log(dictionary[“key1”]); // Output: “value1”
“`
In this example, we are accessing the value corresponding to the “key1” key in the dictionary.
Updating Dictionary Values
You can update the value of a key in a dictionary by assigning a new value to it:
“`
let dictionary = {
“key1”: “value1”,
“key2”: “value2”
};
dictionary[“key1”] = “new value”;
console.log(dictionary); // Output: { “key1”: “new value”, “key2”: “value2” }
“`
In this example, we have updated the value of the “key1” key in the dictionary to “new value”.
Adding and Removing Key-Value Pairs
To add a new key-value pair to a dictionary, you can simply assign a value to a new key:
“`
let dictionary = {
“key1”: “value1”,
“key2”: “value2”
};
dictionary[“key3”] = “value3”;
console.log(dictionary); // Output: { “key1”: “value1”, “key2”: “value2”, “key3”: “value3” }
“`
In this example, we have added a new key-value pair with the key “key3” and the value “value3” to the dictionary.
To remove a key-value pair from a dictionary, you can use the `delete` keyword:
“`
let dictionary = {
“key1”: “value1”,
“key2”: “value2”
};
delete dictionary[“key1”];
console.log(dictionary); // Output: { “key2”: “value2” }
“`
In this example, we have removed the key-value pair with the key “key1” from the dictionary.