The set() method of the Map object in JavaScript sets the value for the passed key in the Map object and returns the Map object.
The syntax of Map.set() method is:
set(key, value)
This set() method of Map sets the value for the passed key in the Map object. Returns the Map object.
Parameter | Optional/Required | Description |
---|---|---|
key | required | The key of the element to add to the Map. |
value | required | The value of the element to add to the Map. |
Map.set() returns value of type Map
.
In JavaScript, we can use the set()
method to add a key-value pair to a Map object.
For example,
map
.set()
method to add the key 'a' with the value 1 to the map
.map
to the console using console.log()
.const map = new Map();
map.set('a', 1);
console.log(map);
Map { 'a' => 1 }
In JavaScript, we can use the set()
method to update the value of an existing key in a Map object.
For example,
map
with an initial key-value pair 'a' => 1.set()
method to update the value of the key 'a' to 2 in the map
.map
to the console using console.log()
.const map = new Map([['a', 1]]);
map.set('a', 2);
console.log(map);
Map { 'a' => 2 }
In JavaScript, we can use the set()
method to add key-value pairs to a Map object where keys can be of different types.
For example,
map
.set()
method to add a key-value pair with a string key 'a' and a value 1 to the map
.set()
method to add a key-value pair with a number key 2 and a value 'b' to the map
.set()
method to add a key-value pair with an object key { key: 'c' }
and a value 3 to the map
.map
to the console using console.log()
.const map = new Map();
map.set('a', 1);
map.set(2, 'b');
map.set({ key: 'c' }, 3);
console.log(map);
Map { 'a' => 1, 2 => 'b', { key: 'c' } => 3 }
In this JavaScript tutorial, we learned about set() method of Map: the syntax and few working examples with output and detailed explanation for each example.