map.values() returns an iterator that gives you every value stored in the Map, one by one, in the order the keys were added. It does not give the keys. The iterator is not an array: wrap it in Array.from() or spread it with [...map.values()] when you need an array. Keys can be any value (SameValueZero).
Remember
map.values() → iterator of values (not keys)
for (const v of map.values()) → loop
Array.from(map.values()) → array
[...map.values()] → array
order = insertion order
iterator can be used only once
Syntax
Call it on a Map. It takes no arguments and is usually used with for...of or Array.from().
JavaScript
map.values()
Call
What it does
map.values()
An iterator of the values of the Map.
Array.from(map.values())
Turn the values into an array.
[...map.values()]
Spread the values into an array.
Built into JavaScript since ES2015. To get keys instead, see keys(). To get both, see entries().
Library declarations
JavaScript
map.values() // returns a Map Iterator of values
// no parameters
// order: insertion order
Parameters
Parameter
Description
(none)
This method takes no parameters. Call it as map.values().
Return Value
Return Value
Description
Map Iterator
An iterator of the stored values, in insertion order. Use it once; call values() again for a second loop.
JavaScript Examples
Example 1 — Loop Over the Values
Print every value with for...of, in the order the keys were added.
JavaScript
const ages = new Map();
ages.set("Ann", 31);
ages.set("Bob", 27);
ages.set("Carl", 40);
for (const age of ages.values()) {
console.log(age);
}
Array.from builds a new array.Array.from(scores.values()) walks the iterator and collects every value.
Spread does the same job.[...scores.values()] also builds an array with the same numbers.
Two separate arrays. The contents match, but from === spread is false because each call creates a new array.
Example 3 — An Iterator Can Be Used Only Once
Store the iterator in a variable. The second loop finds nothing left.
JavaScript
const tags = new Map();
tags.set(1, "a");
tags.set(2, "b");
const it = tags.values();
const first = [];
for (const v of it) {
first.push(v);
}
console.log(first.join(",")); // a,b
const second = [];
for (const v of it) {
second.push(v);
}
console.log(second.length); // 0
console.log([...tags.values()].join(",")); // a,b