map.values()


The map.values() method returns a new iterator object that provides the values for each element in the Map, also in their original insertion order. This is your method of choice when the keys are irrelevant and you only need to work with the values.

Example 1: Basic Value Iteration

// A map of HTTP status codes to their meanings.
const statusCodes = new Map();
statusCodes.set(200, 'OK');
statusCodes.set(404, 'Not Found');
statusCodes.set(500, 'Internal Server Error');

// Iterate over just the values (the meanings).
for (const meaning of statusCodes.values()) {
  console.log(meaning);
}

Explanation This loop uses map.values() to access only the descriptive strings from the statusCodes map. The numeric keys (200, 404, 500) are ignored during this iteration.


Example 2: Summing Numeric Values

// A shopping cart map with products and their quantities.
const cart = new Map();
cart.set('Laptop', 1);
cart.set('Mouse', 2);
cart.set('Keyboard', 1);

// Calculate the total number of items in the cart.
let totalItems = 0;
for (const quantity of cart.values()) {
  totalItems += quantity;
}
console.log(`Total items in cart: ${totalItems}`); // Outputs: 4

Explanation Here, map.values() is used to iterate over the quantities of each item in the cart. This allows for a clean and direct way to sum them up without needing to access the product keys.


Example 3: Iterating Over Array Values

// A map where values are arrays of tags.
const articleTags = new Map();
articleTags.set('Article 1', ['JavaScript', 'ES6']);
articleTags.set('Article 2', ['CSS', 'Flexbox']);

// Iterate through the arrays of tags.
for (const tags of articleTags.values()) {
  // tags is an array: ['JavaScript', 'ES6'], then ['CSS', 'Flexbox']
  console.log(`Tags: ${tags.join(', ')}`);
}

Explanation The values in a Map can be complex data structures like arrays. This example iterates through the values, where each tags variable in the loop is an array that can be further processed.


Example 4: Executing Stored Functions

// A map that stores functions as its values.
const commandQueue = new Map();
commandQueue.set('greet', () => console.log('Hello!'));
commandQueue.set('farewell', () => console.log('Goodbye!'));

// Iterate over the values and execute each function.
for (const command of commandQueue.values()) {
  command(); // Executes the function.
}

Explanation This demonstrates a powerful pattern where functions are stored as map values. The for...of loop with .values() iterates through these functions, allowing each one to be called in sequence.


Example 5: Collecting Values into an Array

// A map of user IDs to usernames.
const users = new Map();
users.set(1, 'alex');
users.set(2, 'beth');
users.set(3, 'charlie');

// Use the spread syntax to get an array of all usernames.
const usernames = [...users.values()];

console.log(usernames); // Outputs: ['alex', 'beth', 'charlie']

Explanation Similar to using .keys(), the spread syntax (...) can be used on the .values() iterator. This offers a very readable and concise way to create an array containing all values from the map.


Example 6: Finding a Specific Value

// A map of file names to their MIME types.
const mimeTypes = new Map();
mimeTypes.set('image.jpg', 'image/jpeg');
mimeTypes.set('data.json', 'application/json');
mimeTypes.set('archive.zip', 'application/zip');

let hasJson = false;
for (const type of mimeTypes.values()) {
  if (type === 'application/json') {
    hasJson = true;
    break; // Exit the loop early once found.
  }
}
console.log(`Does the map contain a JSON file? ${hasJson}`);

Explanation This code iterates through all values to check for the existence of a specific one. Using break makes the search more efficient by stopping the loop as soon as a match is found.


Example 7: Displaying User-Friendly Names

// A map from internal setting keys to display-friendly names.
const settingNames = new Map();
settingNames.set('darkMode', 'Dark Mode');
settingNames.set('emailNotify', 'Email Notifications');

// Display all the friendly names.
console.log('Available Settings:');
for (const friendlyName of settingNames.values()) {
  console.log(`- ${friendlyName}`);
}

Explanation This is a common use case for internationalization or creating user interfaces. The loop uses .values() to get only the display-friendly strings, ignoring the internal programmatic keys.