Map.prototype.set()
map.set(key, value) Returns:
Map · Updated March 13, 2026 · Map and Set map set add
The set() method adds or updates a key-value pair in a Map. It returns the Map itself, enabling method chaining.
Syntax
map.set(key, value)
Parameters
| Parameter | Type | Description |
|---|---|---|
| key | any | The key to set |
| value | any | The value to associate with the key |
Examples
Basic usage
const userRoles = new Map();
userRoles.set('alice', 'admin');
userRoles.set('bob', 'editor');
console.log(userRoles.get('alice'));
// 'admin'
Updating existing values
const scores = new Map();
scores.set('player1', 100);
scores.set('player1', 150); // Updates the value
console.log(scores.get('player1'));
// 150
Method chaining
const userRoles = new Map();
// set() returns the Map, enabling chaining
userRoles.set('alice', 'admin')
.set('bob', 'editor')
.set('charlie', 'viewer');
console.log([...userRoles.entries()]);
// [['alice', 'admin'], ['bob', 'editor'], ['charlie', 'viewer']]
Map with object keys
const visits = new Map();
const page1 = { path: '/home', lang: 'en' };
const page2 = { path: '/home', lang: 'es' };
visits.set(page1, 1500);
visits.set(page2, 800);
console.log(visits.get(page1));
// 1500
Map with various value types
const data = new Map();
data.set('users', ['alice', 'bob']);
data.set('config', { theme: 'dark', lang: 'en' });
data.set('callback', () => console.log('ready'));
console.log(data.get('users'));
// ['alice', 'bob']
console.log(data.get('config').theme);
// 'dark'
data.get('callback')();
// 'ready'
Common Patterns
Caching with Map
function fibonacci(n, cache = new Map()) {
if (cache.has(n)) return cache.get(n);
if (n <= 1) return n;
const result = fibonacci(n - 1, cache) + fibonacci(n - 2, cache);
cache.set(n, result);
return result;
}
console.log(fibonacci(50));
// 12586269025
Building a Map from an object
const obj = { a: 1, b: 2, c: 3 };
const map = new Map(Object.entries(obj));
map.set('d', 4);
console.log(map.get('b'));
// 2
Conditional updates
const inventory = new Map([
['apples', 10],
['bananas', 5]
]);
function addStock(fruit, quantity) {
const current = inventory.get(fruit) || 0;
inventory.set(fruit, current + quantity);
}
addStock('apples', 5);
addStock('oranges', 20);
console.log([...inventory]);
// [['apples', 15], ['bananas', 5], ['oranges', 20]]