JS: the Set Object Tutorial

By Xah Lee. Date: . Last updated: .

What is Set Object

(new in ECMAScript 2015)

A “Set” object are collections of values.

Creating Set

new Set()
Create a empty set.
new Set(iterable)
Create a set from values in iterable object iterable.
new Set([3, 4, 5])
// Set(3) { 3, 4, 5 }

Parent of Set Objects

The parent of any set object is Set.prototype.

Size of Set

Add a Value

Delete a Value

Check Existence

Clear Set

Iteration

Union, Intersection, Difference

Convert Set to Array

Set of Arrays, Set of Objects

Set can contain value of any type. But when elements are objects (or arrays), be careful that two object of same structure and element values is considered different objects.

// set of arrays

// note the array [3] is duplicated, because [3] === [3] returns false
console.log(new Set([4, [3], [3]]));
// Set(3) { 4, [ 3 ], [ 3 ] }

// note here there the [3] is not duplicated
const xx = [3];
console.log(new Set([4, xx, xx]));
// Set(2) { 4, [ 3 ] }

Add Properties to Set

Because set is a object, you can add properties to it. 〔see JS: Object Type

const xx = new Set([4, 5, 6]);

// you can add properties to a set object
xx.pp = 3;

console.log(xx.pp === 3);
console.log(Object.hasOwn(xx, "pp"));

JavaScript. Set Object