To create a map (also known as an object) in JavaScript, you can use curly braces {}
to define and initialize it. Here’s an example:
javascriptCopy code// Create an empty map
var myMap = {};
// Add key-value pairs to the map
myMap["key1"] = "value1";
myMap["key2"] = "value2";
myMap["key3"] = "value3";
// Access values by keys
console.log(myMap["key1"]); // Output: "value1"
console.log(myMap["key2"]); // Output: "value2"
console.log(myMap["key3"]); // Output: "value3"
// Update values
myMap["key2"] = "new value";
// Remove a key-value pair
delete myMap["key3"];
// Check if a key exists in the map
console.log("key1" in myMap); // Output: true
console.log("key3" in myMap); // Output: false
// Get the number of key-value pairs in the map
var size = Object.keys(myMap).length;
console.log(size); // Output: 2
// Iterate over the key-value pairs
for (var key in myMap) {
console.log(key + ": " + myMap[key]);
}
In this example, we create an empty map called myMap
and add key-value pairs using square bracket notation ([]
). You can access the values by their corresponding keys and update or remove them as needed. The in
operator allows you to check if a specific key exists in the map. To get the number of key-value pairs, we use Object.keys(myMap).length
, and to iterate over the map, we use a for...in
loop.
You can customize the keys and values according to your requirements. Maps in JavaScript are flexible and allow different types of keys and values.

Brijpal Sharma is a web developer with a passion for writing tech tutorials. Learn JavaScript and other web development technology.