Careeroza
Map & Set
Set
Example
A Set stores unique values:
const tags = new Set(["js", "css", "js", "html"]);
console.log(tags.size, tags.has("css"));
tags.add("sql").delete("css");
console.log([...tags]);
const unique = [...new Set([3, 1, 3, 2, 1])];
console.log(unique);Output
3 true [ 'js', 'html', 'sql' ] [ 3, 1, 2 ]
Map
Example
A Map is a key/value collection where keys can be any type and insertion order is kept:
const visits = new Map();
visits.set("/home", 10).set("/jobs", 4);
visits.set("/jobs", visits.get("/jobs") + 1);
console.log(visits.get("/jobs"), visits.size);
for (const [page, count] of visits) console.log(page, count);
const objKey = { id: 1 };
visits.set(objKey, "object as a key");
console.log(visits.get(objKey));Output
5 2 /home 10 /jobs 5 object as a key
Object vs Map
| Object | Map | |
|---|---|---|
| Key types | strings and symbols | any value |
| Size | Object.keys(o).length | map.size |
| Iteration order | mostly insertion (integers first) | insertion |
| Best for | fixed records, JSON | dynamic collections, frequent add/remove |