Set.prototype.union()
Baseline 2024Newly available
Since June 2024, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
Theunion() method ofSet instances takes a set and returns a new set containing elements which are in either or both of this set and the given set.
In this article
Syntax
union(other)Parameters
Return value
A newSet object containing elements which are in either or both of this set and theother set.
Description
In mathematical notation,union is defined as:
And using Venn diagram:
union() acceptsset-like objects as theother parameter. It requiresthis to be an actualSet instance, because it directly retrieves the underlying data stored inthis without invoking any user code. Then, it iterates overother by calling itskeys() method, and constructs a new set with all elements inthis, followed by all elements inother that are not present inthis.
The order of elements in the returned set is first those inthis followed by those inother.
Examples
>Using union()
The following example computes the union between the set of even numbers (<10) and the set of perfect squares (<10). The result is the set of numbers that are either even or a perfect square, or both.
const evens = new Set([2, 4, 6, 8]);const squares = new Set([1, 4, 9]);console.log(evens.union(squares)); // Set(6) { 2, 4, 6, 8, 1, 9 }Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-set.prototype.union> |