JavaScript · Lesson 28 / 32 · English
Sets
Understand the idea. Change the code. Build confidence with one focused experiment.
Read this lesson in தமிழ் ↗.
Start with the idea
Set stores unique values. It is useful for deduplicating primitive values and checking membership; objects are compared by identity, not by matching properties.
Learning goal: Explain what the example does, predict its result, and change it to solve the practice task.
Step-by-step lesson notes
Set in JavaScript
A Set is a collection of unique values. It automatically removes duplicates and maintains insertion order.
Working with Sets
const set = new Set([1, 2, 3, 2, 1]);
console.log(set); // Set { 1, 2, 3 } — duplicates removed
set.add(4);
set.add(3); // ignored — already exists
set.delete(1);
set.has(2); // true
set.size; // 3
// Iteration
for (const val of set) {
console.log(val);
}
// Convert to array
const arr = [...set]; // spread
const arr2 = Array.from(set); // Array.from
set.clear(); // remove all
// Most common use: remove duplicates from array
const nums = [1, 2, 2, 3, 3, 3, 4];
const unique = [...new Set(nums)]; // [1, 2, 3, 4]Set Operations
const a = new Set([1, 2, 3, 4]);
const b = new Set([3, 4, 5, 6]);
// Union — all elements from both
const union = new Set([...a, ...b]);
// Set { 1, 2, 3, 4, 5, 6 }
// Intersection — elements in both
const intersection = new Set([...a].filter(x => b.has(x)));
// Set { 3, 4 }
// Difference — elements in a but not b
const difference = new Set([...a].filter(x => !b.has(x)));
// Set { 1, 2 }ES2025 introduces native Set.prototype.union(), intersection(), and difference() methods — no manual implementation needed in modern environments.
A complete example
Run this complete index.js program in the JavaScript console editor below. The earlier reference fragments may need a browser page or other surrounding setup.
const topics = new Set(["arrays", "objects", "arrays"]);
topics.add("functions");
console.log(topics.size);
console.log(topics.has("arrays"));
console.log([...topics].join(", "));Predict first. Reveal the expected result.
3 true arrays, objects, functions
Make one change. See what happens.
Load the example, change a value, predict the output, and run it again. Use the console output to check your reasoning.
Wait for the editor to load, then load this example and press Run.
Powered by the free OneCompiler editor. Code you run is sent to that external service. Keep personal data and secret keys out of your examples.
Put the idea to work
Practice challenge
Delete objects and predict the remaining size.
Reveal the answer and reasoning
topics.delete("objects") removes that member and size becomes 2.
One mistake to avoid: Two separate objects such as {id: 1} and {id: 1} remain different Set members.
Your learning checkpoint
- Explain the example in your own words.
- Complete the challenge before revealing its answer.
- Describe the common mistake and how to avoid it.