HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Maps

A Map is a collection of key-value pairs where the keys can be of any data type. Unlike objects, where keys are usually strings or symbols, a Map key can even be an object or a function.


Essential Map Methods

Maps provide a cleaner and more efficient API for managing key-value data compared to regular objects.

Method Description
new Map() Creates a new Map
set() Sets the value for a key in a Map
get() Returns the value for a key
has() Returns true if a key exists
delete() Removes a Map element
clear() Removes all the elements from a Map

Creating and Setting Values

You can create a Map by passing an array to the new Map() constructor, or add items using the set() method.

// Method 1: Creating with an array
const fruits = new Map([
  ["apples", 500],
  ["bananas", 300]
]);

// Method 2: Using set()
fruits.set("oranges", 200);
fruits.set("apples", 600); // Changes the existing value

Reading and checking values

The get() method retrieves a value, and has() checks for existence.

console.log(fruits.get("bananas")); // 300
console.log(fruits.has("grapes"));  // false

Objects as Keys (Advanced)

The most powerful feature of Maps is that they can use objects as keys. This is something standard objects {} cannot do properly.

const user = { name: "Mim" };
const visits = new Map();

visits.set(user, 5); // Using an object as a key
console.log(visits.get(user)); // 5

Map vs. Object

Feature Object Map
Key Types String or Symbol Any value (including Objects)
Size Manual check required Built-in size property
Order Not strictly guaranteed Maintains insertion order
Performance Better for simple data Better for large collections

Key Points to Remember

  • A Map holds key-value pairs
  • Keys can be anything (strings, numbers, objects)
  • Use set() to add or update and get() to read
  • The size property gives the count of elements immediately
  • Maps are ordered collection—the items come out in the same order they were put in
  • Maps are iterables, making them easy to use with loops and the spread operator