If code repeatedly searches a list for the same kinds of IDs, a Set expresses the membership question directly. It also removes duplicates when uniqueness is part of the data model.

const selectedIds = new Set(savedIds);

function isSelected(id) {
  return selectedIds.has(id);
}

selectedIds.add("item-42");
selectedIds.delete("item-7");

Choose based on how the data is used

  • Use an array when ordering, duplicates, or index-based access matters.
  • Use a Set for unique values and frequent has, add, or delete operations.
  • Convert between the two when an API or UI needs a particular representation.

A Set preserves insertion order, but it is not a substitute for an array when the application relies on list-specific operations.

Measure before optimizing a small collection. Prefer the representation that makes the code's uniqueness and lookup rules easiest to understand.