JavaScript Map set()
Syntax & Examples
Map.set() method
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.
Syntax of Map.set()
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.
Parameters
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. |
Return Type
Map.set() returns value of type Map
.
✐ Examples
1 Using set() to add a key-value pair to a Map
In JavaScript, we can use the set()
method to add a key-value pair to a Map object.
For example,
- Create a new Map object
map
. - Use the
set()
method to add the key 'a' with the value 1 to themap
. - Log the
map
to the console usingconsole.log()
.
JavaScript Program
const map = new Map();
map.set('a', 1);
console.log(map);
Output
Map { 'a' => 1 }
2 Using set() to update a value in a Map
In JavaScript, we can use the set()
method to update the value of an existing key in a Map object.
For example,
- Create a new Map object
map
with an initial key-value pair 'a' => 1. - Use the
set()
method to update the value of the key 'a' to 2 in themap
. - Log the
map
to the console usingconsole.log()
.
JavaScript Program
const map = new Map([['a', 1]]);
map.set('a', 2);
console.log(map);
Output
Map { 'a' => 2 }
3 Using set() with different types of keys
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,
- Create a new Map object
map
. - Use the
set()
method to add a key-value pair with a string key 'a' and a value 1 to themap
. - Use the
set()
method to add a key-value pair with a number key 2 and a value 'b' to themap
. - Use the
set()
method to add a key-value pair with an object key{ key: 'c' }
and a value 3 to themap
. - Log the
map
to the console usingconsole.log()
.
JavaScript Program
const map = new Map();
map.set('a', 1);
map.set(2, 'b');
map.set({ key: 'c' }, 3);
console.log(map);
Output
Map { 'a' => 1, 2 => 'b', { key: 'c' } => 3 }
Summary
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.