Map.prototype.set
Adds or updates an entry in a Map object with a specified key and value
Syntax
map.set(key, value)Parameters
| Parameter | Type | Description |
|---|---|---|
| key | K | The key of the element to add |
| value | V | The value of the element to add |
Return Value
The Map object (allows chaining)
Examples
const map = new Map<string, number>();
map.set('a', 1);
map.set('b', 2);
console.log(map.get('a')); // 1const map = new Map<string, number>()
.set('x', 10)
.set('y', 20)
.set('z', 30);
console.log(map.size); // 3const cache = new Map<string, unknown>();
function memoized(key: string, compute: () => unknown) {
if (!cache.has(key)) cache.set(key, compute());
return cache.get(key);
}Understanding Map.prototype.set
The Map.prototype.set method in JavaScript adds or updates an entry in a Map object with a specified key and value. It belongs to the Map object and is one of the most widely used methods for working with map values in modern JavaScript and TypeScript applications.
The method signature is map.set(key, value). It accepts 2 parameters: key, value. When called, it returns the map object (allows chaining). Understanding when and how to use set() helps you write more expressive, readable code.
Common use cases for Map.prototype.set include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like map-get, map-has, map-delete, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for Map.prototype.set is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
Map.prototype.getReturns the value associated to the specified key, or undefined if there is no corresponding entry
Map.prototype.hasReturns a boolean indicating whether a value associated with the specified key exists in the Map or not
Map.prototype.deleteRemoves the specified element from a Map object by key
Map.prototype.clearRemoves all key-value pairs from the Map object
More Map Methods
Other methods in the Map object
Related Tools
More Map Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.