JS: the Set Object (basics)

By Xah Lee. Date: . Last updated: .

What is Set Object

(new in ECMAScript 2015)

A “Set” object are collections of values.

Create Set

Create a empty set.

// create a empty set
const xx = new Set();
console.log(xx);
// Set(0) {}

// add items
xx.add(8);
xx.add(4);
console.log(xx);
// Set(2) { 8, 4 }

Create a set from values in iterable object.

console.log(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. When elements are objects (or arrays), their reference identity are compared for equality, not their content.

// 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 ] }

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