🟨 JavaScript Intermediate

What is the Set object in JavaScript?

Answer

A Set is a collection of unique values of any type. Duplicate values are automatically removed. Create: const set = new Set([1, 2, 2, 3]) → stores {1, 2, 3}. Methods: add(value), has(value) (O(1) lookup), delete(value), clear(). Properties: size. Sets are iterable in insertion order — for...of, forEach(), spread. Convert array to unique array: const unique = [...new Set(arr)] or Array.from(new Set(arr)). Set operations: union new Set([...a, ...b]), intersection new Set([...a].filter(x => b.has(x))), difference new Set([...a].filter(x => !b.has(x))). Sets do not have index-based access. WeakSet holds objects with weak references. Sets are excellent for: deduplication, tracking visited items, and membership checks where O(1) lookup matters.