Map Methods: keys(), values(), entries()
What You'll Learn
You'll discover how to extract and iterate over just the keys, just the values, or both from a Map using built-in iterator methods.
Why Separate Iterators Matter
When you learned about iterating over Maps, you saw you can loop through them directly. But sometimes you only need the keys, or only the values, or you want explicit control over key-value pairs. Maps provide three methods that return iterators for exactly these scenarios:
map.keys()— returns an iterator of all keysmap.values()— returns an iterator of all valuesmap.entries()— returns an iterator of[key, value]pairs
Using These Methods
const scores = new Map([
['Alice', 95],
['Bob', 82],
['Charlie', 90]
]);
// Get all keys
for (const name of scores.keys()) {
console.log(name); // 'Alice', 'Bob', 'Charlie'
}
// Get all values
for (const score of scores.values()) {
console.log(score); // 95, 82, 90
}
// Get key-value pairs explicitly
for (const [name, score] of scores.entries()) {
console.log(`${name}: ${score}`);
}
Think of It Like a Filing Cabinet
Imagine a filing cabinet where each drawer has a label (key) and contents (value). Sometimes you just need to see all the labels without opening drawers (keys()), sometimes you only care about what's inside (values()), and sometimes you need both label and contents together (entries()).
Note: Iterating directly over a Map (for (const entry of map)) is identical to using map.entries().
Key Takeaway:
Use keys(), values(), and entries() when you need targeted iteration over specific parts of your Map data.