Lesson 44 +15 XP

JavaScript Sets

JavaScript Sets

A Set is a collection of unique values. No value can appear twice.

Creating a Set

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

Add values

colors.add("yellow");
colors.add("red"); // already there, ignored

Sets remove duplicates automatically

const nums = new Set([1, 1, 2, 2, 3]);
nums.size; // 3 (duplicates dropped)

Check membership

colors.has("red"); // true

Remove a value

colors.delete("green");

Size

colors.size;

Loop through a Set

colors.forEach(function(color) {
  console.log(color);
});

TL;DR

  • A Set holds unique values.
  • Duplicates are ignored automatically.
  • add, has, delete, and size manage it.
  • Great for removing duplicates from arrays.