Objects / HashMaps
Objects / HashMaps
"If arrays are lists, objects are dictionaries — you look things up by name, not position. HashMaps are the secret weapon behind O(1) lookups."
Part 1: Key-Value Pairs
An object (or HashMap) stores data as key-value pairs. Instead of using an index like 0, 1, 2, you use a meaningful key like "name" or "age". This lets you look up data instantly — O(1) time.
Creating and reading objects
// Object literal
let user = {
name: "Vivek",
age: 22,
city: "Chennai"
};
// Two ways to read values
console.log(user.name); // Vivek (dot notation)
console.log(user["age"]); // 22 (bracket notation)
// Bracket notation is useful when the key is dynamic
let key = "city";
console.log(user[key]); // ChennaiAdding and updating entries
let obj = { a: 1, b: 2 };
// Add new key
obj.c = 3;
console.log(obj); // { a: 1, b: 2, c: 3 }
// Update existing key
obj.a = 99;
console.log(obj.a); // 99
// Delete a key
delete obj.b;
console.log(obj); // { a: 99, c: 3 }Part 2: Checking Existence and Iterating
Checking if a key exists
let freq = { apple: 3, banana: 1 };
// Option 1: in operator
console.log("apple" in freq); // true
console.log("mango" in freq); // false
// Option 2: !== undefined
console.log(freq["apple"] !== undefined); // true
// Option 3: hasOwnProperty
console.log(freq.hasOwnProperty("banana")); // trueIterating over an object
let scores = { Alice: 92, Bob: 85, Charlie: 78 };
// Keys
for (let name in scores) {
console.log(name, ":", scores[name]);
}
// Object.keys / values / entries
Object.keys(scores).forEach(k => console.log(k)); // ["Alice","Bob","Charlie"]
Object.values(scores).forEach(v => console.log(v)); // [92, 85, 78]
Object.entries(scores).forEach(([k, v]) => {
console.log(`${k} scored ${v}`);
});Most common DSA pattern: frequency count
Count how many times each element appears — used in Two Sum, anagrams, and many more.
let nums = [1, 2, 2, 3, 1, 4, 2];
let freq = {};
for (let n of nums) {
freq[n] = (freq[n] || 0) + 1;
}
console.log(freq);
// { '1': 2, '2': 3, '3': 1, '4': 1 }
// Find which number appears most
let maxCount = Math.max(...Object.values(freq));
console.log("Max frequency:", maxCount); // 3Part 3: Map — the Better HashMap
JavaScript's Map is the dedicated HashMap. It allows any type as a key (not just strings), preserves insertion order, and has a cleaner API than plain objects.
Using Map
let map = new Map();
// set, get, has, delete
map.set("name", "Vivek");
map.set("age", 22);
map.set(42, "the answer"); // number as key — not possible with plain obj!
console.log(map.get("name")); // Vivek
console.log(map.has("age")); // true
console.log(map.size); // 3
map.delete("age");
console.log(map.size); // 2
// Iterate
for (let [key, value] of map) {
console.log(key, "→", value);
}Object references — a common bug
Objects are passed by reference. Two variables can point to the same object — changing one changes the other.
let a = { x: 1 };
let b = a; // b points to the SAME object
b.x = 99;
console.log(a.x); // 99 — a was also changed!
// To copy independently, use spread:
let c = { ...a }; // shallow copy
c.x = 7;
console.log(a.x); // still 99 — a is safeUse plain Object when
Keys are always strings/symbols, structure is known upfront, or you need JSON serialization.
Use Map when
Keys can be any type, you need insertion-order iteration, or you're doing frequent add/delete.
