Skip to content

Set

This lesson explains Set with clear examples, use cases, and best practices so you can use modern JavaScript confidently in real projects.

ES6+ Set Overview

Set is an ES6 collection that stores unique values of any type. Each value can appear only once, which makes Set ideal for removing duplicates, tracking membership, and performing set-based operations.

Set is commonly used to deduplicate arrays, store unique tags, track visited items, compare lists, and answer fast membership questions with has().

Feature Description
Introduced In ES6 (ECMAScript 2015)
Stores Unique values of any type
Main Methods add(), has(), delete(), clear()
Size Property set.size
Iterable Yes — supports for...of
Common Uses Deduplication, tags, membership checks, set operations

Basic Set Example

const tags =
  new Set();

tags.add("javascript");
tags.add("es6");
tags.add("javascript");

console.log(tags);
console.log(tags.size);
console.log(tags.has("es6"));

tags.delete("es6");

console.log(tags.has("es6"));

Adding the same value twice does not create duplicates. Set automatically keeps only unique entries.

How Set Works

Set uses strict equality (===) to determine whether a value already exists. Values are stored once and can be checked, removed, or iterated efficiently.

Step Description Example Syntax
Create Set Start empty or from an iterable. new Set() or new Set(array)
Add Value Insert a unique item. set.add(value)
Check Membership See if a value exists. set.has(value)
Remove Value Delete one item. set.delete(value)
Iterate Values Loop through unique items. for (const item of set)
Clear Set Remove all values. set.clear()

Create a Set from an Array

const numbers = [
  1, 2, 2, 3, 4, 4, 5
];

const uniqueNumbers =
  new Set(numbers);

console.log(uniqueNumbers);
console.log(uniqueNumbers.size);

const dedupedArray = [
  ...uniqueNumbers
];

console.log(dedupedArray);

One of the most common Set patterns is removing duplicates from an array with [...new Set(array)].

Iterate Over a Set

const colors =
  new Set([
    "red",
    "green",
    "blue"
  ]);

for (const color of colors) {
  console.log(color);
}

colors.forEach((color) => {
  console.log(color);
});

console.log([
  ...colors.values()
]);

Set is iterable, so you can use for...of, forEach(), and spread syntax to process its values.

Fast Membership Checks

const allowedRoles =
  new Set([
    "admin",
    "editor",
    "viewer"
  ]);

function canAccess(role) {
  return allowedRoles.has(role);
}

console.log(canAccess("editor"));
console.log(canAccess("guest"));

set.has() is useful when you need to check whether a value exists in a collection of allowed options.

Set with Objects and Mixed Values

const userA = { id: 1 };
const userB = { id: 2 };
const userC = { id: 1 };

const users =
  new Set([
    userA,
    userB,
    userC
  ]);

console.log(users.size);

const mixed =
  new Set([
    1,
    "1",
    true,
    NaN,
    NaN
  ]);

console.log(mixed.size);
console.log(mixed.has(NaN));

Set compares object references, not deep object content. Two different objects with the same data are treated as different values. Unlike arrays, Set treats NaN consistently with has().

Set Union Example

const frontend = [
  "HTML",
  "CSS",
  "JavaScript"
];

const backend = [
  "JavaScript",
  "Node.js",
  "Express"
];

const union = [
  ...new Set([
    ...frontend,
    ...backend
  ])
];

console.log(union);

A union combines values from multiple collections and keeps only unique results.

Set Intersection Example

const groupA =
  new Set(["Alex", "Sam", "Riya"]);

const groupB =
  new Set(["Sam", "Riya", "Jo"]);

const intersection = [
  ...groupA
].filter((name) =>
  groupB.has(name)
);

console.log(intersection);

Intersection finds values that exist in both sets. This pattern is useful for comparing user selections, permissions, or shared tags.

Set Difference Example

const allTags =
  new Set([
    "javascript",
    "react",
    "node",
    "css"
  ]);

const selectedTags =
  new Set([
    "react",
    "css"
  ]);

const remainingTags = [
  ...allTags
].filter(
  (tag) =>
    !selectedTags.has(tag)
);

console.log(remainingTags);

Difference finds values present in one set but not another. This helps with filtering, exclusions, and comparison logic.

Common Set Methods and Properties

Method / Property Description Example
add(value) Adds a unique value. set.add("js")
has(value) Checks whether a value exists. set.has("js")
delete(value) Removes a value. set.delete("js")
clear() Removes all values. set.clear()
size Returns number of values. set.size
forEach() Loops through each value. set.forEach(fn)

Common Set Use Cases

  • Removing duplicate values from arrays.
  • Storing unique tags, categories, or skills.
  • Tracking visited pages, users, or IDs.
  • Checking allowed roles or permissions quickly.
  • Comparing lists with union, intersection, and difference.
  • Collecting unique form selections or filters.

Set Best Practices

  • Use Set when uniqueness matters more than order or index access.
  • Prefer [...new Set(array)] for simple deduplication.
  • Use has() for fast membership checks.
  • Remember that object equality is based on reference, not deep value.
  • Convert back to an array only when array methods are needed.
  • Use descriptive variable names such as uniqueTags or allowedRoles.
  • Clear or recreate sets when resetting state in applications.

Common Set Mistakes

  • Expecting Set to compare object contents instead of references.
  • Using Set when order-sensitive array behavior is required.
  • Forgetting that add() returns the Set itself, not a new Set.
  • Assuming Set automatically sorts values.
  • Trying to access values by index like an array.
  • Not converting a Set back to an array when index-based access is needed.
  • Using arrays for membership checks when a Set would be clearer and faster.

Set vs Array

Feature Set Array
Duplicates Not allowed. Allowed.
Index Access No. Yes.
Membership Check set.has(value) array.includes(value)
Best For Unique values and fast lookup. Ordered lists and indexed data.

Set vs Map

Feature Set Map
Stores Unique values only. Key-value pairs.
Main Question "Is this value present?" "What value belongs to this key?"
Common Use Deduplication and membership. Lookup tables and mappings.

Key Takeaways

  • Set is an ES6 collection for storing unique values.
  • Use add(), has(), delete(), and clear() to manage values.
  • [...new Set(array)] is a simple deduplication pattern.
  • Set supports iteration with for...of and forEach().
  • Choose Set for uniqueness and membership, not indexed ordered lists.

Pro Tip

If your first step is "remove duplicates" or "check if this value already exists", try Set before reaching for nested loops or repeated includes() checks.