JS Maps
JS Maps
A Map stores key-value pairs, and keys can be any type (strings, numbers, objects, functions). This makes Map a strong alternative to plain objects in many cases.
const map = new Map();
map.set("name", "Ozan");
map.set("age", 30);
console.log(map.get("name"));
console.log(map.size);
Unlike objects, Maps preserve insertion order and have built-in size.
Object vs Map (Modern Tip)
Use an object for structured data with known property names. Use a Map for dynamic keys, frequent additions/removals, or when keys are not strings.
const obj = {};
obj[1] = "one";
console.log(Object.keys(obj)); // ["1"] (keys become strings)
const m = new Map();
m.set(1, "one");
console.log(m.get(1)); // "one"
JS Map Methods
Common Map methods include set, get, has, delete, clear, and iteration.
const users = new Map();
users.set(1, { name: "Ali" });
users.set(2, { name: "Veli" });
console.log(users.has(2)); // true
console.log(users.get(1).name); // Ali
users.delete(2);
console.log(users.size); // 1
Iterate with for...of using entries(), or directly on the map.
const m2 = new Map([
["a", 1],
["b", 2]
]);
for (const [key, value] of m2) {
console.log(key, value);
}
You can get arrays of keys/values/entries.
console.log([...m2.keys()]); console.log([...m2.values()]); console.log([...m2.entries()]);
JS Map WeakMap
WeakMap is similar to Map, but keys must be objects and the entries do not prevent garbage collection. WeakMap is not iterable and has no size.
WeakMap is commonly used for private data associated with objects.
const privateData = new WeakMap();
let user = { id: 1 };
privateData.set(user, { token: "abc123" });
console.log(privateData.get(user).token);
user = null; // object can be garbage-collected
JS Map Reference
Maps are ideal for key-value data with fast lookups and flexible key types. Key methods include set(), get(), has(), delete(), clear(), and iteration via for...of.
Next Step
Continue with JS Iterations to learn modern looping patterns over arrays, sets, and maps.