JS: the Set Object Tutorial

By Xah Lee. Date: . Last updated: .

What is Set Object

(new in JS: 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.
const xx = new Set([3, 4, 5]);
console.log(xx);
// 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 array

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

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

Add Properties to Set

Because set is a object, you can add properties to it. 〔see 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(xx.hasOwnProperty("pp"));

JavaScript. Set Object