Map.values()

The Map.values() method in JavaScript returns a new iterator object that contains the values of each element in a Map object in insertion order.

Syntax

</>
Copy
map.values()

Parameters

The values() method does not take any parameters.

Return Value

The method returns a new MapIterator object that contains the values for each element in the Map, in insertion order.


Examples

1. Getting Values from a Map

This example demonstrates how to use the values() method to retrieve the values from a Map.

</>
Copy
const map = new Map();
map.set('a', 10);
map.set('b', 20);
map.set('c', 30);

const valuesIterator = map.values();
console.log([...valuesIterator]);

Output

[10, 20, 30]
  1. map.values() returns an iterator containing the values of the Map in insertion order.
  2. The spread operator [...valuesIterator] converts the iterator into an array.

2. Iterating Over Map Values

The values() method is often used with a for...of loop to iterate over the values.

</>
Copy
const map = new Map([
    ['x', 100],
    ['y', 200],
    ['z', 300]
]);

for (const value of map.values()) {
    console.log(value);
}

Output

100
200
300
  1. The for...of loop iterates over each value in the Map.
  2. Each value is logged to the console.

3. Using values() with Array.from()

You can use Array.from() to convert the iterator into an array.

</>
Copy
const map = new Map([
    ['one', 'apple'],
    ['two', 'banana'],
    ['three', 'cherry']
]);

const valuesArray = Array.from(map.values());
console.log(valuesArray);

Output

[ 'apple', 'banana', 'cherry' ]

Array.from(map.values()) creates an array from the values in the Map.