New to Rust? Grab our free Rust for Beginners eBook Get it free →
Set Values in JavaScript: Methods and Operations

JavaScript code may need to keep track of distinct values. A Set stores one member for each value under JavaScript’s equality rules and lets you check membership.
I’ll show how to read Set values and combine collections when the target runtime supports those methods.
TL;DR: Read and Combine Set Values
A JavaScript Set stores distinct values, preserves insertion order when iterated, and provides membership checks plus methods for combining collections.
- Use new Set(iterable) to build a collection and automatically discard repeated primitive values.
- Use size, has(), and values() to inspect it.
- Use union(), intersection(), difference(), and symmetricDifference() when supported by the target runtime.
- To replace a primitive member, delete the old value and add its replacement.
What Is a JavaScript Set?
A Set is a built-in collection that keeps one member for each value under JavaScript’s equality rules.
Pass an iterable to the constructor. For example, new Set([“red”, “blue”, “red”]) contains two strings in first-appearance order.
JavaScript uses SameValueZero for primitive comparisons, so NaN matches NaN and the two zero signs match.
For example, the value “search” can label one feature in a settings list.
For object properties, pass Object.keys() or Object.values() to the constructor.
How to Use Set Values and Methods Step by Step
Build a Set from the values you need to track, then inspect membership and iterate its values. The examples below use Node.js and include a complete run that shows the results.
Step 1: Create a Set and remove duplicate values
Build from the input values, then convert only if the next operation needs array methods.
const colors = new Set(["blue", "red", "blue"]);
console.log([...colors]);
Keep the array conversion only when the next step needs array operations.
Step 2: Check membership and the Set size
The size property reports member count, and has(value) checks for a matching member. This named-file example prints both checks.
console.log(colors.size);
console.log(colors.has("red"));
console.log(colors.has("green"));
2
true
false
Output: 2, true, false. size is a property, so write colors.size.
Step 3: Iterate values or convert the iterator
The default iterator yields each member in insertion order, which is the order in which values were added. keys() is an alias for values().
for (const color of colors.values()) {
console.log(color);
}
const colorArray = Array.from(colors);
console.log(colorArray);
The loop prints blue, then red. Convert with Array.from(set) when you need array operations.
Step 4: Add, delete, and clear members
The add() method returns the Set, while delete() reports whether it removed a member. clear() empties the collection.
const tasks = new Set(["review", "test"]);
const sameSet = tasks.add("deploy");
console.log(sameSet === tasks);
console.log(tasks.delete("test"));
tasks.clear();
console.log(tasks.size);
The printed values are true, true, and 0, in that order. The final size confirms the collection is empty.
Step 5: Combine sets with built-in operations
Set composition returns a new Set. Union keeps members from either input, intersection keeps shared members, difference keeps left-side members, and symmetric difference keeps members present in exactly one input.
const first = new Set(["read", "write", "share"]);
const second = new Set(["share", "archive"]);
console.log([...first.union(second)]);
console.log([...first.intersection(second)]);
console.log([...first.difference(second)]);
console.log([...first.symmetricDifference(second)]);
The outputs are [ ‘read’, ‘write’, ‘share’, ‘archive’ ], [ ‘share’ ], [ ‘read’, ‘write’ ], and [ ‘read’, ‘write’, ‘archive’ ].
The union output contains members from both inputs.

I ran node set_values_demo.js and got the same results, including two distinct object references in the final check. The output shows why equal-looking object fields do not make separately allocated objects the same Set member.
values: [ 'blue', 'red' ]
size: 2
has red: true
union: [ 'read', 'write', 'share', 'archive' ]
intersection: [ 'share' ]
first minus second: [ 'read', 'write' ]
symmetric difference: [ 'read', 'write', 'archive' ]
distinct object references: 2
Set Edge Cases and Compatibility
Set behavior depends on equality rules, iterator return types, and support in the JavaScript engine that runs your code. Check these details before selecting an operation or relying on object uniqueness.
To retrieve a member by position, convert the Set to an array or iterate until that position.
There are two common tasks behind “change a value.” Replacing a primitive means removing one member and adding another. Updating a property on an object means changing that object, which remains the same reference in the collection.
For example, a set of selected category names is suited to membership checks. If each category also needs an editable label, storing records in a Map keyed by category ID gives the update a stable address.
Deleting a missing value is safe and reports false. This is useful when cleanup code may run more than once: the caller can distinguish the first successful removal from a later no-op without checking membership separately.
Use clear() when the whole collection is obsolete, and delete one value when only that member should go.
Convert when an API requires an array, sorting is needed, or array transformations clarify the next operation. A loop can handle members directly when no second container is useful.
For a string such as “book”, iteration yields code points, so repeated letters appear once. Combined emoji can contain multiple code points, so use grapheme-aware segmentation for user-facing text.
Native set-composition methods accept set-like operands, not only another Set. A set-like value supplies size, has(), and keys(), which lets compatible map-shaped collections participate. Check the method documentation when passing a custom object, because a plain iterable alone does not guarantee the required interface.
Composition does not mutate either input. Keep the result if it represents a new derived group, or call add() and delete() on the original when the task is to update that group’s membership. This distinction prevents later code from assuming an input changed when only a result was produced.
Older browsers or embedded engines may not provide a method that Node supports. Feature detection lets code choose a fallback, which should return the type callers expect and follow the same membership rules. Include overlapping values and values found on only one side in tests.
A Set is often a good fit for a temporary “already seen” check while processing records. Before adding a record’s category, call has() to decide whether that category has appeared. The same membership test can prevent duplicate tags in a generated result.
When an array is the input, deduplication is a transformation, not an in-place edit. Keep the original array if another part of the program depends on duplicates or source order beyond the first occurrence. If the transformed list is the intended value, assign the converted result to a clearly named variable.
A Map keyed by the needed field provides a stable way to enforce uniqueness across separately created records.
A Set of numeric user IDs supports repeat checks. For object members, membership follows reference identity, so separately parsed records for one user may remain distinct.
For union and intersection, decide which side should control the output order. These methods return sets, so iteration is useful when that order feeds a later display. If the result is sorted alphabetically, convert it to an array and sort that array rather than expecting Set itself to provide sorting.
has() and delete() return booleans that can guide conditional logic. The add() method returns the Set, allowing chained calls.
Replace a Set member
To replace a primitive member, delete its old value and add the replacement.
const names = new Set(["Ada", "Lin"]);
if (names.delete("Ada")) names.add("Ada Lovelace");
For updates by identifier, use a Map keyed by that identifier. Mutating an object property leaves its reference in the Set.
Matching object contents do not mean matching identity
const item = { id: 1 };
const records = new Set([item, item, { id: 1 }]);
console.log(records.size);
console.log(records.has({ id: 1 }));
A Map keyed by an object field handles uniqueness across separate records.
A values() result is an iterator
const labels = new Set(["alpha", "beta"]);
const upper = Array.from(labels, (label) => label.toUpperCase());
Use Array.from() to transform yielded values, as in the probe below.
Check support before using native set operations
MDN marks composition methods as Baseline 2024, while older engines may lack them. Test the methods on the runtime you deploy to.
if (typeof first.union === "function") {
console.log([...first.union(second)]);
} else {
console.log([...new Set([...first, ...second])]);
}
The fallback combines iterables and passes them through the constructor. For intersection or difference, filter with has() and wrap the result in a Set when downstream code expects one.
I checked native operations against an array-filter intersection in Node.js v26.7.0. Both returned the shared value 3, and the runtime reported the native union, intersection, and difference methods as available.
The composition result is a separate collection, so assign it when subsequent work needs the combined members.
const combined = first.union(second);
first.add("publish");
first.delete("read");
Conclusion
A form can gather labels from several controls and check membership before displaying a summary. When repeated selections carry meaning, keep them in an array so those repetitions remain available.
Use a Set for membership checks, an array for positional access, and a Map for values addressed by keys.
For exact behavior, see the MDN Set reference and its values() reference. To explore related JavaScript collection choices, read CodeForGeek’s Map guide and TypeScript overview.
FAQ
These answers cover common questions about reading and changing Set values.
How do you get values from a Set in JavaScript?
Use for…of with the Set or call values() to get an iterator. Convert it with Array.from(set) or […set] when an array is needed.
Can you change a value in a JavaScript Set?
A Set has no index-based replacement. Delete the old primitive value and add the replacement, or use a Map when values are updated by key.
Why can a Set contain two objects with the same properties?
Objects are compared by reference identity. Two separate object literals are different references even when their properties match.
Does JavaScript Set have union and intersection methods?
Modern Set implementations provide union(), intersection(), difference(), symmetricDifference(), and related comparison methods. Check the target runtime because older engines may lack them.




