Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Set.prototype.difference — set difference

The difference() method returns a new Set containing elements of the receiving set that are absent from the other set. It preserves their order and does not itself modify the input sets.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

set.difference(other)

Set.prototype.difference computes set difference: a.difference(b) contains elements of a that are absent from b. Operand order matters — this is not symmetric difference. The result is a new Set preserving the insertion order of the remaining elements of a; the operation itself does not change the input sets.

The this receiver must be an actual Set object. The other argument can be a set or a set-like object: it must expose a valid size and callable has() and keys() methods. Map satisfies this protocol, and its keys are compared. Being iterable alone is insufficient: first pass an array to new Set(...).

For ordinary sets, equality follows SameValueZero: NaN matches NaN, +0 and -0 are equivalent, and objects are compared by identity, not contents. Depending on the sizes, the algorithm uses other.has() or iterates over other.keys(). Custom methods and getters can therefore cause side effects; do not assume their call sequence is independent of size.

The method belongs to ECMAScript 2025, not Web APIs. When deploying, check typeof Set.prototype.difference === "function" in the target environment. The specification is not a browser-support table, and Node 24 being present in a repository does not establish browser support.

Examples

const available = new Set([3, 1, 2]);
const reserved = new Set([1, 4]);
const remaining = available.difference(reserved);

console.log(JSON.stringify([...remaining]));
console.log(JSON.stringify([...available]));
console.log(JSON.stringify([...reserved]));

Result

[3,2]
[3,1,2]
[1,4]

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources