JavaScript ‘Map’ and ‘Set’ Constructor

Definition
Both Set() and Map() are nothing but two different types of object maker I mean ‘constructor’ introduced in ES6.
- Set() constructor is used to store unique values of any type.
- Map() constructor is used to store key-value pairs where both key and value can be any type of data.
[N. B: We can also store any type of value with key-value pairs in an object. But key must be stored in string data type.]
Clarification of Definition with Example
Example of set constructor to understand practically

In the above example, ‘Set’ constructor is used to remove duplicate items from the array. And ‘spread operator’ is used to convert the object into an array. By the way, as ‘Set’ is a constructor, we had to convert the object ‘removingDuplicate’ into an array. Because constructor makes object.
Example of map constructor to understand practically

In the above example, you can see that the structure of ‘Map’ constructor is like multi-dimensional array. But if you see key-value pairs, it looks like an object syntactically there are so many differences. Now look at the keys in every pair. In first pair, key is a data of string type. But in second and third ones, keys are of number and bool types.
If we think now about javascript object, we can find out a silly difference between object and map with the syntactical differences. The keys of object can be only of string data types. But in ‘Map’ constructor you can use keys in any type of data even in ‘Map’ constructor keys can be of object.
Example of map constructor to understand it with more clarification

In the above example, besides string, number, and bool you can see an object as a key of ‘Map’ constructor. Like that you can also use array as a key in ‘Map’ constructor. And that’s main reason to introduce the map constructor in ES6.
Methods and Properties
Set() Methods and Properties
1. add(value)
let set= new set();
set.add('name'); // with string value
set.add(1); // with number value
set.add(true); // with boolean value
console.log(set); // result : Set(3) {"name", 1, true}
2. has(value)
set.has(true); // to check that specific value has or not
3. size
console.log(set.size); result : 3
4. delete(value)
set.delete(true); // to delete an item
5. clear()
set.claer(); to delete all items at a time
Map() Methods and Properties
1. set(key, value)
let map = new Map();
map.set('1', 'str1'); // with string key
map.set(1, 'num1'); // with number key
map.set(true, 'bool'); // with boolean key
console.log(map); // result: Map(3) {"1" => "str1", 1 => "num1", true => "bool"}
2. get(key)
console.log(map.get(1)); // result : num1
3. has(key)
console.log(map.has(bool)); // return : true
4. size
console.log(map.size); // result : 3
5. delete(key)
map.delete(1); // to delete an item
6. clear()
map.clear(); // to delete everything at a time
Iteration Methods on Set and Map
- keys()
- values()
- entries()
We can also iterate with for...of
loop on them.