Map and Set
Map and Set in JavaScript
The Map and Set data structures were introduced in ECMAScript 2015 (ES6) and are designed for more flexible and powerful data storage compared to regular objects and arrays.
Map is a collection of key-value pairs. It's similar to an object but has several advantages.
const myMap = new Map();
myMap.set("name", "Ani");
myMap.set("age", 30);
console.log(myMap.get("name")); // Ani
console.log(myMap.has("age")); // true
console.log(myMap.size); // 2
myMap.delete("age");
console.log(myMap.has("age")); // false
Features and advantages:
.set
, .get
, .has
, .delete
methodsSet is a collection of values where duplicate values are not allowed.
const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(2); // Will be ignored because it already exists
console.log(mySet.has(1)); // true
console.log(mySet.size); // 2
mySet.delete(2);
console.log(mySet.has(2)); // false
Features and advantages:
Property | Object / Array | Map / Set |
---|---|---|
Key/value types | string or number | Any (objects, functions) |
Maintains insertion order | Not always | Yes |
Data lookup speed | Slow for large amounts | Fast |
Duplicate values | Allowed | Set - no, Map - keys are unique |
Map is the best choice when you need to store key-value pairs, while Set is ideal when you need to store only unique values. They are more convenient and performant than regular objects and arrays, especially when managing complex data.
M