Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 14.3 — Map and Set
JavaScript · Example 1 of 3 ES2015+

Map keys of any type, and the object trap

{ id: 1 } written again is a new object, so the Map doesn't find it. In the plain object, 1 became "1" and both objects became "[object Object]", so b overwrote a.

Map is a key-value collection whose keys can be any value (objects included) and which remembers insertion order; Set is a collection of unique values. Both are iterable, have a real size, and are built for frequent adding, looking up and removing.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write firstRepeat(list) that returns the first value that appears a second time, using a Set. firstRepeat(["a", "b", "c", "b", "a"]) should return "b".

02

Given const orders = [["tea", 2], ["pen", 1], ["tea", 3]], build a Map of total quantity per item and log it.

03

Two classes share some students: const x = new Set(["Asha", "Ravi", "Meera"]) and const y = new Set(["Ravi", "Kabir"]). Log the students in both, and everyone in either.

Explain it without notes

01

When would you choose a Map over a plain object?

02

How do Map and Set compare keys and values? What happens with NaN and with objects?

03

How do you remove duplicates from an array, and what are the limits of that method?

04

Name the ES2025 set methods and say what each returns.

Map keys of any type, and the object trap ES2015+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

4
number one | string one
an object
undefined
Map(3) { '1' => 'string one', 1 => 'number one', { id: 1 } => 'an object' }
[ '1', '[object Object]' ]
object b