Junior
Tell about the map and set methods in JavaScript.
sobes.tech AI
Answer from AI
Map — a collection of key-value pairs, where keys can be of any data type, unlike objects where keys can only be strings or Symbols. Supports iteration in insertion order.
// Example of using Map
const myMap = new Map();
myMap.set('name', 'Alice');
myMap.set(1, 'one');
console.log(myMap.get('name')); // Alice
console.log(myMap.size); // 2
myMap.delete(1);
console.log(myMap.has(1)); // false
Set — a collection of unique values of any type. Supports iteration in insertion order.
// Example of using Set
const mySet = new Set();
mySet.add(1);
mySet.add('hello');
mySet.add(1); // Duplicate will not be added
console.log(mySet.size); // 2
console.log(mySet.has('hello')); // true
mySet.delete(1);
console.log(mySet.has(1)); // false
Main differences:
| Attribute | Map | Set |
|---|---|---|
| Purpose | Storing key-value pairs | Storing unique values |
| Access | By key (get) | Checking existence (has) |
| Size | Number of pairs (size) | Number of unique values (size) |
| Keys/Values | Keys and values can be of any type | Only values, any types |