Problem Statement
What is the main difference between Map and Object?
Explanation
Map allows any data type as keys including objects, functions, and primitives. Objects only allow strings and symbols as keys.
Map maintains insertion order of keys. Objects do not guarantee order, though modern engines maintain it.
Map has a size property. Objects need Object.keys for length.
Map performs better for frequent additions and deletions. Objects are optimized for static property access.
Map is iterable by default with forEach, for of. Objects need Object.keys or Object.entries.
Use Map for key-value storage with non-string keys or when order matters.
Code Solution
SolutionRead Only
// MAP - any type as key
const map = new Map();
// Object as key
const keyObj = {id: 1};
map.set(keyObj, 'value');
// Function as key
const keyFunc = () => {};
map.set(keyFunc, 'function value');
// Primitive as key
map.set(1, 'number key');
map.set('name', 'string key');
console.log(map.get(keyObj)); // 'value'
console.log(map.get(1)); // 'number key'
// OBJECT - only string/symbol keys
const obj = {};
obj[keyObj] = 'value'; // Converts to '[object Object]'
obj[1] = 'value'; // Converts to '1'
console.log(obj[keyObj]); // 'value'
console.log(obj['[object Object]']); // 'value' (same!)
// MAP METHODS
const map2 = new Map();
// Set value
map2.set('name', 'John');
map2.set('age', 30);
// Get value
console.log(map2.get('name')); // 'John'
// Check if key exists
console.log(map2.has('name')); // true
// Delete key
map2.delete('age');
// Size
console.log(map2.size); // 1
// Clear all
map2.clear();
// ITERATION
const map3 = new Map([
['a', 1],
['b', 2],
['c', 3]
]);
// forEach
map3.forEach((value, key) => {
console.log(key, value);
});
// for...of
for (const [key, value] of map3) {
console.log(key, value);
}
// Keys, values, entries
console.log([...map3.keys()]); // ['a', 'b', 'c']
console.log([...map3.values()]); // [1, 2, 3]
console.log([...map3.entries()]); // [['a',1], ['b',2], ['c',3]]
// SET - unique values
const set = new Set();
set.add(1);
set.add(2);
set.add(2); // Duplicate ignored
set.add(3);
console.log(set.size); // 3
console.log(set.has(2)); // true
set.delete(2);
set.clear();
// Array to Set (remove duplicates)
const arr = [1, 2, 2, 3, 3, 4];
const uniqueSet = new Set(arr);
const uniqueArr = [...uniqueSet];
console.log(uniqueArr); // [1, 2, 3, 4]
// PRACTICAL EXAMPLES
// Cache with Map
const cache = new Map();
function memoizedFunction(key) {
if (cache.has(key)) {
return cache.get(key);
}
const result = expensiveOperation(key);
cache.set(key, result);
return result;
}
// DOM elements as keys
const elementData = new Map();
const button = document.getElementById('btn');
elementData.set(button, {clicks: 0, lastClick: null});
// Unique values with Set
const usernames = new Set();
usernames.add('john');
usernames.add('jane');
if (usernames.has('john')) {
console.log('Username taken');
}
// WEAKMAP and WEAKSET
// WeakMap - keys are objects, garbage collected
const weakMap = new WeakMap();
let obj2 = {id: 1};
weakMap.set(obj2, 'data');
obj2 = null; // Object can be garbage collected
// WeakSet - values are objects, garbage collected
const weakSet = new WeakSet();
let obj3 = {id: 1};
weakSet.add(obj3);
obj3 = null; // Object can be garbage collected