JavaScript Map set() method

The set method in JavaScript's Map object is utilized to insert or modify an entry within the map by associating it with a specific key-value pair. It is essential that each value corresponds to a distinct key.

Syntax

The syntax for the set method is as follows:

Example

mapObj.set(key,value)

Parameter

key - It represents the key to be added.

value - It represents the value to be added.

Return

The Map object.

JavaScript Map set method example

In this section, we will explore the set method using a range of examples.

Example 1

Let's explore an example that demonstrates how to insert key-value pairs into a map object.

Example

<script>

var map=new Map();

map.set(1,"jQuery");

map.set(2,"AngularJS");

map.set(3,"Bootstrap");

document.writeln(map.get(1)+"<br>");

document.writeln(map.get(2)+"<br>");

document.writeln(map.get(3));

</script>

Output:

Output

jQuery

AngularJS

Bootstrap

Example 2

In this illustration, we will explore the outcome that occurs when identical keys are combined with varying values.

Example

<script>

var map=new Map();

map.set(1,"jQuery");

map.set(1,"AngularJS");

map.set(3,"Bootstrap");

document.writeln(map.get(1)+"<br>");

document.writeln(map.get(2)+"<br>");

document.writeln(map.get(3));

</script>

Output:

Output

AngularJS

undefined

Bootstrap

Input Required

This code uses input(). Please provide values below: