๐ŸŽ“ A1Learner
๐Ÿ”

JavaScript Sets

A Set is a collection that holds each value only once. Adding a value that is already present changes nothing.

Duplicates vanish

The input array holds six numbers. The size shows that only three values remain.

const nums = new Set([1, 2, 2, 3, 3, 3]);
console.log(nums.size);

Add a value twice

The second add of the same word does nothing. The size grows only once for that word.

const tags = new Set();
tags.add("new");
tags.add("new");
tags.add("sale");
console.log(tags.size);

Check and list values

has answers membership questions. Spread turns the set back into an array.

const colors = new Set(["Red", "Blue", "Red"]);
console.log(colors.has("Blue"));
console.log(colors.has("Green"));
console.log([...colors]);

Example

const letters = new Set(["a", "b", "a", "c", "b"]);
console.log(letters.size);
letters.add("d");
letters.add("a");
console.log(letters.size);
console.log([...letters]);

Key points

  • new Set builds a set from an array.
  • Duplicate values in the input appear once in the set.
  • The size property reports how many values the set holds.
  • add puts a new value into the set.
  • has returns true when the value is in the set.
  • A Set has no indexes, so items are not read by position.

In this example, the set starts with three letters because the repeats are dropped. Adding d raises the size to four. Adding a again changes nothing, and the spread lists the letters in first-seen order.

Note

spreading a set into brackets gives an array in first-seen order.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What is the size of new Set([5, 5, 5])?