Map.prototype.keys()
map.keys() The keys() method returns a new Iterator object containing all the keys in the Map, in insertion order. This complements values() and entries(), giving you a dedicated way to access just the key side of each entry without carrying along the associated values.
Because the return value is an iterator (not an array), it is lazy by default. You can spread it into an array, pass it to Array.from(), or consume it with a for...of loop depending on what you need to do with the keys.
Syntax
map.keys()
Parameters
None. The method takes no arguments and returns a fresh iterator each time it is called. Because Maps preserve insertion order, the iterator will always visit keys in the sequence they were added — this guarantee holds regardless of key type, including numeric keys that behave differently in plain objects.
Return value
A new Iterator object that yields each key in the Map in insertion order.
Examples
Getting all keys as an array
const userRoles = new Map([
['alice', 'admin'],
['bob', 'editor'],
['charlie', 'viewer']
]);
console.log([...userRoles.keys()]);
// ['alice', 'bob', 'charlie']
Spreading into an array gives you a snapshot, but you can also consume the iterator directly in a for...of loop without materializing an intermediate collection. This is the more memory-efficient approach when you only need to inspect each key once and don’t need array methods.
Iterating with for…of
const settings = new Map([
['theme', 'dark'],
['language', 'en'],
['notifications', true]
]);
for (const key of settings.keys()) {
console.log(key);
}
// theme
// language
// notifications
The keys are visited in the same order they were inserted. Maps preserve insertion order, unlike plain objects which have more complex ordering rules. You can also spread the iterator into an array and use array inspection methods like includes to test for key membership without calling has(), though has() is more direct and performant.
Check if Map has a specific key
const cache = new Map([
['users', []],
['config', {}]
]);
const allKeys = [...cache.keys()];
console.log(allKeys.includes('users')); // true
console.log(allKeys.includes('cache')); // false
Beyond simple membership checks, converting the key iterator to an array opens up the full pipeline of Array.prototype methods. You can filter keys by their associated values, map them into new shapes, or reduce them into aggregates — operations that Map’s built-in iteration does not support directly.
Use with Array methods
const products = new Map([
['apple', 1.5],
['banana', 0.75],
['orange', 2.0]
]);
const expensiveProducts = [...products.keys()].filter(key => products.get(key) > 1);
console.log(expensiveProducts);
// ['apple', 'orange']
Converting keys to an array lets you use the full suite of Array.prototype methods — filter, map, reduce, and so on — against the key set. However, Map also provides its own forEach method that iterates over both keys and values in a single pass, which can be more convenient when you need to work with the value alongside each key.
Get keys with forEach
const sessions = new Map([
['session1', { user: 'alice' }],
['session2', { user: 'bob' }]
]);
sessions.forEach((value, key) => {
console.log(`Session ${key}: ${value.user}`);
});
Note that forEach on a Map provides (value, key, map) — the value comes first, unlike the typical (element, index) pattern in Array.prototype.forEach.
Insertion order and predictability
Maps keep their keys in the order they were inserted, which makes keys() useful when order matters as much as lookup. That predictability is one reason Maps are easier to reason about than plain objects in code that needs stable iteration. If you are generating menus, serializing configuration, or comparing ordered sets of identifiers, the keys() iterator gives you a reliable sequence without having to sort first.
When to materialize an array
Because keys() returns an iterator, you do not pay for an array until you ask for one. That is helpful when you want to inspect only part of the sequence or hand the iterator straight to a for...of loop. Convert to an array only when you need array-specific methods or want to snapshot the keys at a particular moment. Keeping the iterator lazy can make large Maps cheaper to inspect.
Common patterns
Find keys that pass a test
const roles = new Map([
['alice', 'admin'],
['bob', 'editor'],
['charlie', 'admin'],
['dave', 'viewer']
]);
const admins = [...roles.keys()].filter(name => roles.get(name) === 'admin');
console.log(admins); // ['alice', 'charlie']
Filtering keys by their associated values is a common operation that keys() combined with array methods handles well. When you only need to check whether a key exists and retrieve its value, get() with a nullish fallback is simpler and avoids materializing the entire key set into an array.
Key existence check before operation
const permissions = new Map([
['read', true],
['write', false]
]);
function canPerform(action) {
return permissions.get(action) ?? false;
}
console.log(canPerform('read')); // true
console.log(canPerform('delete')); // false
Insertion order
Maps preserve the insertion order of their keys. When you call keys(), the iterator yields keys in the exact order they were added. This is guaranteed by the specification and makes Maps reliable for ordered dictionaries, unlike plain objects whose key ordering has subtle edge cases around integer-like keys and inherited properties.
const m = new Map();
m.set('z', 1);
m.set('a', 2);
m.set('m', 3);
console.log([...m.keys()]); // ['z', 'a', 'm'] — insertion order, not sorted
Beyond inspecting keys for their own sake, keys() is useful when debugging or verifying Map-based index structures. Inspecting the keys of an index Map lets you confirm which records were indexed and spot duplicates or missing entries without iterating over every value.
Using keys() to build index structures
function buildIndex(records, keyField) {
const index = new Map();
for (const record of records) {
index.set(record[keyField], record);
}
return index;
}
const users = [
{ id: 'u1', name: 'Alice' },
{ id: 'u2', name: 'Bob' }
];
const byId = buildIndex(users, 'id');
console.log([...byId.keys()]); // ['u1', 'u2']
console.log(byId.get('u1').name); // 'Alice'
Inspecting the keys of an index Map lets you verify which records were indexed and troubleshoot duplicate or missing entries.