JS: the Set Object Tutorial

By Xah Lee. Date: . Last updated: .

New in ES2015.

“Set” objects are collections of values.

Creating Set

new Set() → creates a empty set.

new Set(iterable) → create a set from values in iterable object iterable.

const s = new Set([3,4,5]);
// Set { 3, 4, 5 }

[see JS: Iterable]

[see JS: Set Constructor]

Parent of Set Objects

The parent of any set object is Set.prototype.

[see JS: Prototype and Inheritance]

[see JS: Set.prototype]

Size of Set

set_obj.size → returns the total count of values in set_obj.

[see JS: Set.prototype.size]

Add a Value

set_obj.add(value) → add an value to the set. Returns the modified set.

[see JS: Set.prototype.add]

Delete a Value

set_obj.delete(value) → delete a value in the set. Returns true if found, else false.

[see JS: Set.prototype.delete]

Check Existence

set_obj.has(value) → return true if value is in set. Else, false.

[see JS: Set.prototype.has]

Clear Set

set_obj.clear() → delete all values of the set. Returns undefined.

[see JS: Set.prototype.clear]


Use for-of loop to go thru set instance.

for (let v of set obj { console.log(v); }

[see JS: for-of Loop]

Iteration with forEach

JS: Set.prototype.forEach

Union, Intersection, Difference

JS: Set Union, Intersection, Difference

Convert Set to Array

Use Array.from(set)

[see JS: Array.from]

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.

[see JS: Test Equality of Objects]

// set of array

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

const x = [3];
const s2 = new Set([4, x, x]);
console.log(s2); // Set { 4, [ 3 ] }
// array assigned to variable is ok

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 JS: Object Type]

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

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

console.log(Object.getOwnPropertyNames(s)); // [ 'pp' ]

JS Set

  1. Set Tutorial
  2. Union, Intersection, Difference

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials