Map.set()
The Map.set()
method in JavaScript is used to add or update key-value pairs in a Map
object. If the key already exists, its value is updated; otherwise, a new key-value pair is added.
Syntax
</>
Copy
map.set(key, value)
Parameters
Parameter | Description |
---|---|
key | The key to be added or updated in the Map . |
value | The value associated with the specified key. |
Return Value
The set()
method returns the updated Map
object, allowing method chaining.
Examples
1. Adding Key-Value Pairs
This example demonstrates how to add key-value pairs to a Map
.
</>
Copy
const map = new Map();
map.set('name', 'Arjun');
map.set('age', 25);
map.set('city', 'New York');
console.log(map);
Output
Map(3) { 'name' => 'Arjun', 'age' => 25, 'city' => 'New York' }
set('name', 'Arjun')
adds a key-value pair where'name'
is the key and'Arjun'
is the value.- Each call to
set()
updates theMap
with a new entry.
2. Updating an Existing Key
If the key already exists, its value is updated instead of adding a new entry.
</>
Copy
const map = new Map();
map.set('name', 'Arjun');
map.set('name', 'Bhairav'); // Updates the value for 'name'
console.log(map.get('name'));
Output
Bhairav
set('name', 'Arjun')
initially adds the key-value pair.set('name', 'Bhairav')
updates the value associated with'name'
.
3. Using Non-String Keys
The Map
object allows keys of any type, including objects and functions.
</>
Copy
const map = new Map();
const objKey = { id: 1 };
const funcKey = () => {};
map.set(objKey, 'Object Value');
map.set(funcKey, 'Function Value');
console.log(map.get(objKey));
console.log(map.get(funcKey));
Output
Object Value
Function Value
The set()
method successfully stores values with object and function keys.
4. Chaining set()
Calls
Since set()
returns the Map
object, multiple calls can be chained together.
</>
Copy
const map = new Map()
.set('a', 1)
.set('b', 2)
.set('c', 3);
console.log(map);
Output
Map(3) { 'a' => 1, 'b' => 2, 'c' => 3 }
Chaining allows for cleaner and more readable code.