JavaScript

This page explains JavaScript Set, a collection that keeps each value only once.

Goal: use Set's unique-value behavior to add, remove, and check values without manually searching for duplicates.

Set

A Set stores unique values. It can contain numbers, strings, objects, and other values, and it remembers insertion order when you iterate through it.

Remove duplicates

JavaScript

const categories = ["book", "game", "book"];
const uniqueCategories = new Set(categories);

console.log(uniqueCategories); // Set(2) { "book", "game" }
console.log(uniqueCategories.size); // 2

Basic operations

JavaScript

const tags = new Set();

tags.add("javascript");
tags.add("web");
tags.add("javascript"); // no duplicate is added

console.log(tags.has("web")); // true
tags.delete("web");
console.log(tags.size);        // 1

tags.clear();

Set or array?

Use a Set when uniqueness and fast membership checks are central. Use an array when duplicate values, indexes, or array methods such as filter() and map() are important. Convert a Set back to an array with [...tags] when needed.

Related topics