Modern JavaScript and a project · Lesson 42 of 45
Map and Set
Keys of any type, and lists without duplicates.
7 minutes2 games
- Set is a list where nothing repeats:
add,has,delete,size. - Map is like an object whose keys can be any type (numbers, objects…), keeps insertion order and has
size:set,get,has.
JavaScript
const tags = new Set(["js", "css", "js", "html", "css"])
console.log(tags.size, tags.has("js"))
console.log([...tags])
const visits = new Map()
visits.set("/home", 3)
visits.set("/courses", 7)
visits.set("/home", visits.get("/home") + 1)
console.log(visits.get("/home"), visits.size)
for (const [page, n] of visits) console.log(page, n)| Object | Map | |
|---|---|---|
Key types | strings (and symbols) | any type |
Size |
|
|
Frequent add/delete | fine | faster |
JSON-friendly? | yes | not directly |
What's the output?
const s = new Set([1, 2, 2, 3, 3, 3]) console.log(s.size)
What will this code print?
Exercise
Print how many different students submitted (3).
Expected output: 3
JavaScript
const submissions = ["ali", "mona", "ali", "omar", "mona"]
Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.