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 s = new Set([3,4,5]);
console.log(s);
// Set { 3, 4, 5 }

[see Iterable]

[see Set Constructor]

Parent of Set Objects

The parent of any set object is Set.prototype.

[see Prototype and Inheritance]

[see Set.prototype]

Size of Set

set_obj.size

[see Set.prototype.size]

Add a Value

set_obj.add(value)

[see Set.prototype.add]

Delete a Value

set_obj.delete(value)

[see Set.prototype.delete]

Check Existence

set_obj.has(value)

[see Set.prototype.has]

Clear Set

set_obj.clear()

[see Set.prototype.clear]

Iteration

Use for-of loop to go thru set instance.

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

[see for-of Loop]

Iteration with forEach

Set.prototype.forEach

Union, Intersection, Difference

Set Union, Intersection, Difference

Convert Set to Array

Use Array.from(set)

[see 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 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 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' ]

JavaScript Set Object

βˆ‘ JS in Depth
XAH Β BUY NOW

JS in Depth

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc