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

Map Advantages: Non-String Keys and Iteration Order

Explore Map's ability to use any value as a key and guarantee insertion-order iteration.

Map Advantages: Non-String Keys and Iteration Order

You'll learn why Maps excel at using any type of key and guaranteeing predictable iteration.

The Core Advantages

When you learned about Maps, you saw they accept "any value as a key" and support iteration. Now let's understand why these features make Maps powerful compared to plain objects.

Non-String Keys: True Flexibility

Plain objects convert all keys to strings. If you use a number or object as a key, JavaScript silently converts it. Maps don't do this — they preserve the actual type and value:

const userScores = new Map();
const player1 = { name: 'Alice' };
const player2 = { name: 'Bob' };

// Objects AS keys (not converted to strings!)
userScores.set(player1, 100);
userScores.set(player2, 85);

console.log(userScores.get(player1)); // 100 ✓

This lets you associate data with actual objects, DOM elements, or even functions — something impossible with regular objects.

Guaranteed Insertion Order

Maps remember the exact order you added entries. When you iterate (using for...of, forEach, or .entries()), you always get keys in the sequence they were first set:

const timeline = new Map();
timeline.set('morning', 'coffee');
timeline.set('noon', 'lunch');
timeline.set('evening', 'dinner');

for (const [time, meal] of timeline) {
  console.log(`${time}: ${meal}`);
}
// Logs in exact insertion order: morning, noon, evening

While modern JavaScript objects often maintain order, Maps guarantee it by specification. This makes Maps reliable for ordered collections where sequence matters.

Key Takeaway: Maps shine when you need non-string keys (especially objects) or must guarantee iteration order — two scenarios where plain objects either fail or offer weaker guarantees.