← All languages
JavaScript function of the day

Map.prototype.set

Add or update an entry in a Map with a specified key and value.

Description

The set() method adds or updates an entry in a Map object with a specified key and a value, and returns the Map object. This allows for method chaining with other Map operations.

Unlike plain objects, Map keys can be any value, including objects, functions, and primitives. Maps maintain insertion order, so entries are iterated in the order they were added.

The set() method uses the SameValueZero algorithm for key comparison, which treats NaN as equal to NaN (unlike ===). If the key already exists, its value is updated; otherwise, a new entry is created.

Arguments

NameDescriptionOptional
key The key of the element to add or update. No
value The value of the element to add or update. No

Example

const map = new Map();
map.set('name', 'Alice');
map.set('age', 30);
map.get('name');  // 'Alice'

Reference