In JavaScript, the closest equivalents to a HashMap (from other languages like Java or C++) are:

  • Object – a collection of key–value pairs where keys are strings or symbols.
  • Map – introduced in ES6, allows keys of any type and maintains insertion order.

Option 1: Using Object (Traditional):

const userDetails = {
 name: "Alice",
 age: 30,
 role: "Developer"
};
// Accessing values
console.log(userDetails["name"]); // Alice

// Adding a new key
userDetails["location"] = "New York";

// Iterating
for (const key in userDetails) {
 console.log(`${key}: ${userDetails[key]}`);
}

Option 2: Using Map (Recommended for most use-cases)

const userMap = new Map();
// Setting key-value pairs
userMap.set("name", "Bob");
userMap.set("age", 25);
userMap.set("role", "Designer");

// Getting values
console.log(userMap.get("name")); // Bob
// Checking if a key exists
console.log(userMap.has("age")); // true
// Iterating
userMap.forEach((value, key) => {
 console.log(`${key}: ${value}`);
});

Summary

Use Map if:

  • You need keys other than strings.
  • You care about insertion order.
  • You want better built-in iteration and performance.

 
Use Object if:

  • You only need simple key-value pairs with string keys.
  • You need to serialize easily using JSON.

Need Help With Javascript Development?

Work with our skilled Javascript developers to accelerate your project and boost its performance.

Hire JavaScript Developers

Support On Demand!

Related Q&A