JavaScript: the Set Object Tutorial

By Xah Lee. Date: . Last updated: .

New in JS2015.

β€œSet” objects 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 ss = new Set([3, 4, 5]);
console.log(ss);
// Set { 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 ss = new Set([4, [3], [3]]);
console.log(ss); // Set { 4, [ 3 ], [ 3 ] }

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

Add Arbitrary Properties to Set

Because set is a object, you can still add arbitrary properties to a set object. (but you shouldn't do it.) [see Object Type]

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

// you can add arbitrary properties to a set object
ss.pp = 3;
console.log(ss.pp === 3);

console.log(ss.hasOwnProperty("pp"));

JavaScript Set Object

BUY Ξ£JS JavaScript in Depth