JavaScript Maps

Creating a Map

A Map is a collection of key–value pairs where keys can be of any data type, and entries maintain their insertion order.

const myMap = new Map();

You can also create a Map with initial values:

const myMap = new Map([
  ["name", "Alice"],
  ["age", 25]
]);

Setting and Getting Values

console.log(myMap.get("name"));  // "Alice"

Use set() to add a key-value pair, and get() to retrieve a value.

Checking and Deleting Keys

console.log(myMap.has("age"));   // true
myMap.delete("age");             // removes the key "age"

has() returns a boolean, delete() removes a key.

Size Property and Clear Method

console.log(myMap.size);  // number of key-value pairs
myMap.clear();             // removes all entries

Iterating Over a Map

Use forEach or for...of to loop through a Map:

Loading...
Output:

Map vs Object

  • Maps can have any type as keys (objects, functions, etc.)
  • Map maintains insertion order; Object does not
  • Maps are better for frequent additions and deletions

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic