Add or update an entry in a Map with a specified key and value.
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.
| Name | Description | Optional |
|---|---|---|
key |
The key of the element to add or update. | No |
value |
The value of the element to add or update. | No |
const map = new Map();
map.set('name', 'Alice');
map.set('age', 30);
map.get('name'); // 'Alice'