Hello friends! When you store data in a JavaScript Map, sooner or later you will want a list of just the keys. That is exactly what keys() is for. The keys() method of a JavaScript Map returns an iterator over all the keys in the map, in the order they were inserted. It takes no arguments and does not change the map.
map.keys()
The important word is iterator. keys() does not return an array, so you cannot call .length or .filter() on it directly. You loop over it with for...of, or convert it to an array first. Let’s understand both with simple examples.
Basic Example
const marks = new Map([["Riya", 91], ["Aman", 78], ["Kabir", 85]]);
const keyIter = marks.keys();
console.log(keyIter.next().value);
console.log(keyIter.next().value);
Output:
Riya
Aman
Each call to next() moves one step forward and returns an object like { value: "Riya", done: false }. When there are no keys left, done becomes true.
Looping Over Keys with for…of
Calling next() by hand is good for understanding, but in real code you will rarely do it. The most common way to use keys() is a for...of loop:
for (const name of marks.keys()) {
console.log(name);
}
Output:
Riya
Aman
Kabir
Converting Keys to an Array
Use the spread operator or Array.from() when you need array methods:
console.log([...marks.keys()]);
console.log(Array.from(marks.keys()));
const toppers = [...marks.keys()].filter(n => marks.get(n) > 80);
console.log(toppers);
Output:
[ 'Riya', 'Aman', 'Kabir' ]
[ 'Riya', 'Aman', 'Kabir' ]
[ 'Riya', 'Kabir' ]
Keys Keep Their Insertion Order
Now here is something that makes Maps really handy. A Map remembers the order in which keys were added, whatever their type:
const m2 = new Map();
m2.set("z", 1);
m2.set("a", 2);
m2.set(10, 3);
console.log([...m2.keys()]);
Output:
[ 'z', 'a', 10 ]
Compare this with a plain object, where number-like keys are moved to the front and every key becomes a string:
const obj = { 2: "b", 1: "a", x: "c" };
console.log(Object.keys(obj));
Output:
[ '1', '2', 'x' ]
Keys Can Be Any Type
Unlike object keys, Map keys keep their real type. The number 1 and the string "1" are two different keys:
const objKey = { id: 1 };
const m3 = new Map([[1, "number"], ["1", "string"], [true, "boolean"], [objKey, "object"]]);
for (const k of m3.keys()) console.log(typeof k, k);
Output:
number 1
string 1
boolean true
object { id: 1 }
The Iterator Is “Live”
If you add keys to the map before you finish reading the iterator, the new keys show up too:
const m4 = new Map([["a", 1]]);
const it = m4.keys();
m4.set("b", 2);
console.log([...it]);
Output:
[ 'a', 'b' ]
If you need a fixed snapshot, convert to an array first with [...map.keys()].
keys() vs values() vs entries()
keys() has two close cousins, and it helps to see all three side by side:
console.log([...marks.values()]);
console.log([...marks.entries()]);
console.log(marks.size);
Output:
[ 91, 78, 85 ]
[ [ 'Riya', 91 ], [ 'Aman', 78 ], [ 'Kabir', 85 ] ]
3
| Method | Gives you |
|---|---|
keys() |
only the keys |
values() |
only the values |
entries() |
[key, value] pairs (also what for...of on the map itself gives) |
size |
the number of entries (a property, not a method) |
Common Mistakes
Beginners often trip over these three things, so keep them in mind:
- Treating the result as an array.
marks.keys().lengthisundefined. Usemarks.size, or[...marks.keys()].length. - Reusing a finished iterator. Once you have looped through an iterator, it is empty. Call
marks.keys()again to start over. - Using
Object.keys(map). That returns[]for a Map, because Map entries are not object properties.
So friends, to sum up: map.keys() gives you every key in insertion order as an iterator. Loop over it with for...of, and when you need array methods, just spread it into an array with [...map.keys()]. Try the examples above in your browser console, and you will get comfortable with it in a few minutes.
Related: Map in JavaScript · Map has() · Map get() · for…of loop