JavaScript Map values()
Syntax & Examples

Map.values() method

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


Syntax of Map.values()

The syntax of Map.values() method is:

values()

This values() method of Map returns a new Iterator object that contains the values for each element in the Map object in insertion order.

Return Type

Map.values() returns value of type Iterator.



✐ Examples

1 Using values() to iterate over a Map

In JavaScript, we can use the values() method to get an iterator object and use it to iterate over the values of a Map.

For example,

  1. Create a new Map object map with initial key-value pairs.
  2. Use the values() method to get an iterator object iterator for the map.
  3. Use a for...of loop to iterate over the iterator and log each value to the console using console.log().

JavaScript Program

const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
const iterator = map.values();
for (const value of iterator) {
  console.log(value);
}

Output

1
2
3

2 Using values() to convert a Map to an array of values

In JavaScript, we can use the values() method to convert a Map object to an array of values.

For example,

  1. Create a new Map object map with initial key-value pairs.
  2. Use the values() method to get an iterator object iterator for the map.
  3. Convert the iterator to an array using the Array.from() method and store it in the variable arrayOfValues.
  4. Log arrayOfValues to the console using console.log().

JavaScript Program

const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
const iterator = map.values();
const arrayOfValues = Array.from(iterator);
console.log(arrayOfValues);

Output

[ 1, 2, 3 ]

3 Using values() with a Map of objects

In JavaScript, we can use the values() method to iterate over a Map object containing objects as values.

For example,

  1. Create a new Map object map with initial key-value pairs where values are objects.
  2. Use the values() method to get an iterator object iterator for the map.
  3. Use a for...of loop to iterate over the iterator and log each value to the console using console.log().

JavaScript Program

const map = new Map([
  ['person1', { name: 'John' }],
  ['person2', { name: 'Jane' }]
]);
const iterator = map.values();
for (const value of iterator) {
  console.log(value);
}

Output

{ name: 'John' }
{ name: 'Jane' }

Summary

In this JavaScript tutorial, we learned about values() method of Map: the syntax and few working examples with output and detailed explanation for each example.