JavaScript Map set() Method Tutorial

In this section, we will learn what the Map set() method is and how to use it in JavaScript.

What is JavaScript Map set() Method?

The `set()` method adds or updates elements in a Map object.

JavaScript Map set() Method Syntax:

set(key, value)

set() Function Parameters:

The method takes 2 arguments:

  • The first argument is the value that we want to set for the key.
  • The second argument is the value that we want to set for the value part.

Note: if the key that is entered into the target map already exists in that map; the execution engine will replace the old value of that key with the new value that we set as the second argument of this method.

set() Function Return Value:

The return value of this method is a reference to the Map object that we just set a key value for it with this method.

Example: using Map set() method in JavaScript

const map = new Map();
map.set("John","222-22222222");
map.set(22 , 2000);
map.set(true, false); 
map.set("Jack", "333-3234232");

console.log(map.get("John"));
console.log(map.get(22))

Output:

222-22222222

2000

Note: the execution engine remembers the order in which keys entered to the target map. So in this program, the first key that is stored on the map is “John”, the second one is `22`, the third one is `true` and the last one is `Jack`.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies