Hash Map
A key-value store that uses a hash function to achieve O(1) average-case lookup, insertion, and deletion.
Syntax
const map = new Map(); Parameters
| Name | Type | Required | Description |
|---|---|---|---|
iterable | Iterable<[key, value]> | null | No | An optional iterable of [key, value] pairs to pre-populate the map. Accepts any type as key, unlike plain objects. |
Returns
Map — A new Map instance.
Examples
// Frequency count
const words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple'];
const freq = new Map();
for (const w of words) freq.set(w, (freq.get(w) ?? 0) + 1);
console.log([...freq.entries()].sort((a, b) => b[1] - a[1]));
Output
[ [ 'apple', 3 ], [ 'banana', 2 ], [ 'cherry', 1 ] ]
// Two-sum using a hash map
function twoSum(nums, target) {
const seen = new Map();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (seen.has(complement)) return [seen.get(complement), i];
seen.set(nums[i], i);
}
return [];
}
console.log(twoSum([2, 7, 11, 15], 9));
Output
[ 0, 1 ]
Notes
| Operation | Best | Avg | Worst | Space |
|----------|------|------|-------|-------|
| Get | O(1) | O(1) | O(n) | O(n) |
| Set | O(1) | O(1) | O(n) | O(n) |
| Delete | O(1) | O(1) | O(n) | O(1) |
| Has | O(1) | O(1) | O(n) | O(1) |
Worst case O(n) occurs when all keys hash to the same bucket
(collision attack). JavaScript's `Map` preserves insertion order
and accepts any value (including objects) as a key, unlike
plain object literals which coerce keys to strings.