Map

Map.prototype.set

Adds or updates an entry in a Map object with a specified key and value

Syntax

JavaScript
map.set(key, value)

Parameters

ParameterTypeDescription
keyKThe key of the element to add
valueVThe value of the element to add

Return Value

The Map object (allows chaining)

Examples

Basic Usage
const map = new Map<string, number>();
map.set('a', 1);
map.set('b', 2);
console.log(map.get('a')); // 1
Practical Example
const map = new Map<string, number>()
  .set('x', 10)
  .set('y', 20)
  .set('z', 30);
console.log(map.size); // 3
Advanced Usage
const 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

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.