Course contentsShow
← JavaScript
Lesson 1031 of 2,72324. Maps and SetsFree lesson

What is a Map and Why Use It?

Understanding Map as a key-value collection and when it's better than plain objects.

What is a Map and Why Use It?

You'll learn: What a Map is in JavaScript and when to prefer it over plain objects for storing key-value pairs.

Understanding Map as a Key-Value Collection

A Map is a built-in JavaScript data structure that stores key-value pairs, similar to objects. However, Maps offer important advantages that make them better choices in certain situations.

Think of a Map like a dictionary where you can look up definitions (values) by words (keys). Unlike a real dictionary that only uses words, a Map lets you use any type as a key — not just strings or symbols.

Why Use Map Instead of Objects?

Plain objects have limitations:

  • Keys are always strings or symbols — If you try obj[5] = 'five', the key 5 becomes the string "5"
  • Prototype pollution risks — Objects inherit properties from Object.prototype, so keys like "toString" can cause conflicts
  • No built-in size property — You need Object.keys(obj).length to count properties
  • Order isn't guaranteed historically — Though modern engines maintain insertion order, it wasn't always reliable

Maps solve these problems:

  • Any type as keys — Use numbers, objects, functions, or even other Maps as keys without conversion
  • No inherited properties — Maps are clean; they only contain what you put in them
  • Built-in size tracking — Maps have a .size property
  • Guaranteed insertion order — Iteration always follows the order you added entries
  • Better performance — Maps are optimized for frequent additions and deletions

When to Choose Map

Use Maps when you need non-string keys, when key names might conflict with object properties, when you frequently add/remove entries, or when insertion order matters for iteration.

Key Takeaway: Maps are specialized key-value collections that accept any data type as keys and provide better performance and reliability than plain objects for dynamic collections.