Course contentsShow
← JavaScript
Lesson 1033 of 2,72324. Maps and SetsFree lesson

Setting Key-Value Pairs

Adding entries to a Map with the set() method and method chaining.

Setting Key-Value Pairs

You'll learn how to add entries to a Map using the set() method and chain multiple calls together efficiently.

How It Works

Once you've created a Map, you populate it with data using the set() method. This method takes two arguments: a key and a value. Unlike plain objects, your keys can be any type—numbers, strings, objects, even functions.

const userPreferences = new Map();

userPreferences.set('theme', 'dark');
userPreferences.set('fontSize', 16);
userPreferences.set('notifications', true);

Each call to set() adds or updates an entry in the Map. If the key already exists, its value gets replaced.

Method Chaining

Here's the elegant part: set() returns the Map itself, allowing you to chain multiple calls together:

const config = new Map()
  .set('host', 'localhost')
  .set('port', 3000)
  .set('secure', false);

This chaining pattern makes initialization cleaner and more readable, especially when setting up a Map with several entries at once.

Updating Values

Setting a key that already exists simply overwrites the previous value:

const scores = new Map();
scores.set('player1', 100);
scores.set('player1', 150); // Updates to 150

Key Takeaway: Use the set(key, value) method to add or update Map entries, and chain multiple set() calls for cleaner initialization since each call returns the Map itself.