JavaScript Sets & Maps

Unique values and key-value collections.

✍️ 3 exercises + code challenge in this lesson

Set

A Set stores unique values. Adding a duplicate does nothing.

  • add(), has(), delete(), size

A common trick: remove duplicates from an array with [...new Set(array)].

Map

A Map stores key-value pairs where keys can be any type, and it remembers insertion order.

  • set(), get(), has(), delete(), size

Key Takeaways: JavaScript Sets & Maps

Mastering JavaScript Sets & Maps helps you write clean and reliable JavaScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

JavaScript Sets & Maps Code Example

JavaScript
<pre id="out"></pre>
<script>
const log = (...a) => document.getElementById("out").textContent += a.join(" ") + "\n";
const tags = new Set(["js", "css", "js", "html", "css"]);
tags.add("python");
log("Set:", [...tags].join(", "), "| size:", tags.size);
log("Has css?", tags.has("css"));

const unique = [...new Set([3, 1, 3, 2, 1])];
log("Unique:", unique);

const prices = new Map();
prices.set("Keyboard", 2500).set("Mouse", 1200);
log("Mouse costs", prices.get("Mouse"));
for (const [item, price] of prices) log(item, "=", price);
</script>
Free sign-in required · Google login available

JavaScript Sets & Maps Practice Exercises

Check what you learned in “JavaScript Sets & Maps”.

/ 3 solved
Fill in the blank

Remove duplicates from an array.

const unique = [...new (list)];
✓ Correct! Not quite. Try again.
Multiple choice

Which Map method reads a value by its key?

✓ Correct! Not quite. Try again.
Code challenge

Log the number of unique values in [1, 2, 2, 3, 3, 3].

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services