# Map and Set in JavaScript 

Map and set are built in data structures that are used to store ordered collections of data, where set holds unique values map holds the data key-value pairs.

**What is Map?**

Stores data as key-value pairs where keys can be any data type. Maintains insertion order for the entries.

const map = new Map()

map.set('name', 'Ansh');

map.set(1, 'Number key');

map.set(true, 'Boolean key');

console.log(map.get('name'))

Output: Ansh

Map can be thought as a powerful version of objects.

**What is Set?**

Set is collection of values accessed without keys and no duplicate entries allowed. Can be thought as a poweful version of array.

const set = new Set(\[1,2,2,3\])

console.log(set);

**When to use set of map in JavaScript**

*   Depends on how the data needs to be accessed. Use map when you need key-value pairs and use set when you need unique values only.
    
*   Use map when keys are not strings or when you frequently add or remove operations from the code.
    
*   Use set when you want to remove duplicates easily.
    
*   Use map when you need guaranteed insertion order.
    

**Map vs Object**

| Feature | Map | Object |
| --- | --- | --- |
| Key types | Any (string, number, object) | Only strings & symbols |
| Order | Maintains insertion order | Not guaranteed |
| Performance | Optimised for frequent operations | Slower for large data |

**Set vs Array**

| Feature | Set | Array |
| --- | --- | --- |
| Duplicates | Not allowed | Allowed |
| Index access | No | Yes |

Eg. How set ignores the duplicates:

const numbers = new Set();  
  
numbers.add(1);  
numbers.add(1);  
numbers.add(2);  
  
console.log(numbers); //output is {1,2}

**Comparison of Map with key-value storage**

key value storage simply means storing data like key -> value, like if I want to assign a value to my key name, it will be name -> Ansh. Instead of using indexes we access data using keys.

Map fulfils the purpose: const user = new Map();

user.set("name", "Ansh"); user.set("age", 25);

console.log(user.get("name")); // Ansh

.set(key, value) is how you store data and .get(key) is hoe you retrieve data.

In case of objects, they also store key-value pairs but they need everything to be converted into string.
