Interesting Facts about JavaScript Set (original) (raw)

Last Updated : 13 Nov, 2024

Let us talk about some interesting facts about JavaScript Set that can make you an efficient programmer.

Internal Working

Sets internally use hash table which makes set an important choice for problems where we want to store distinct keys with efficient search, insert and delete operations. Please note that a hash table data structure allows these operations in constant time on average. Please refer Internal Working of Set in JavaScript for details

Maintains Insertion Order

In Set, the items are maintained according to insertion order. We we access these items, we get in the same order.

JavaScript `

const s = new Set(); s.add(1); s.add(2); s.add(3);

console.log(s);

`

Stores Unique Values

The primary feature of a Set is that it stores only unique values. If you try to add a duplicate value to a Set, it won’t be added again, and the size of the Set stays the same. This feature makes Set ideal for situations where you want to store values without duplicates, such as when collecting distinct elements from an array.

JavaScript `

const s = new Set(); s.add(1); s.add(2); s.add(2);

console.log(s.size);

`

Extra Care of Uniqueness for Primitives

// Set takes extra care for primitive // types. +0 and -0 are considered same // Multiple occurrences of NaN are considered same const s = new Set();

// Adding +0 and -0 to the Set s.add(+0); s.add(-0);

console.log(s.size); console.log([...s]);

// All three are treated same s.add(NaN); s.add(5 + NaN); s.add(5 + NaN); s.add(Math.sqrt(-1));

console.log(s.size); console.log([...s]);

`

Output

1 [ 0 ] 2 [ 0, NaN ]

Uniqueness for Non-Primitives

For non-primitive elements, specifically objects, uniqueness is based on reference equality rather than content equality:

JavaScript `

const s = new Set();

const obj1 = { name: 'Alice' }; const obj2 = { name: 'Alice' }; // identical properties to obj1

s.add(obj1); s.add(obj2);

console.log(s.size); console.log(s.has(obj1)); console.log(s.has(obj2)); console.log([...s]);

`

Output

2 true true [ { name: 'Alice' }, { name: 'Alice' } ]

Set Objects Are Iterables

Just like arrays and Map objects, Set objects are iterable, which means you can loop through the values in a Set using methods like forEach() or a for...of loop.

JavaScript `

const s = new Set([1, 2, 3, 4]); for (let val of s) { console.log(val); }

`

Stores Any Data Type

A Set can store any data type: primitive types like numbers and strings, as well as objects, arrays, and even functions.

JavaScript `

const s = new Set(); s.add(10); s.add("JS"); s.add([1, 2, 3]); s.add({ name: "GFG" });

console.log(s);

`

Output

Set(4) { 10, 'JS', [ 1, 2, 3 ], { name: 'GFG' } }

Maintain Order of Insertion

Unlike arrays, a Set does not have any index-based ordering. However, it does maintain the order of insertion when you iterate over it, which means it iterates through the elements in the order they were added, but you cannot access them using an index.

JavaScript `

const s = new Set(); s.add(30); s.add(20); s.add(10);

for (let val of s) { console.log(val); }

`

Efficient to Check If an Element Exists in a Set

Checking if an item exists in a Set is simple and efficient with the has() method. This method returns a boolean indicating whether a specific value is present in the Set.

JavaScript `

const s = new Set([10, 20, 30]); console.log(s.has(20)); console.log(s.has(40));

`

Adding and Removing Items in a Set

Adding and removing elements in a Set is straightforward. You can use the add() method to add new values and the delete() method to remove them.

JavaScript `

const s = new Set([1, 2, 3]); s.add(4);
s.delete(2);

console.log(s);

`

Remove Duplicates from Arrays

One of the most common use cases for a Set is to remove duplicates from an array. By converting an array to a Set, all duplicates will automatically be removed, leaving only unique elements.

JavaScript `

const a = [1, 2, 2, 3, 4, 4, 5];

// Creating array b containing unique // elements of a using set const b = [...new Set(a)];

console.log(b);

`

WeakSet: A Specialized Version of Set

In addition to the standard Set, JavaScript also offers a WeakSet, which is similar but with one key difference: it only allows objects as values, and the objects are held weakly, meaning they can be garbage collected if there are no other references to them.

JavaScript `

let obj = { name: 'GFG' }; const w = new WeakSet(); w.add(obj);

console.log(w.has(obj));

// The object is now eligible for garbage collection obj = null;

`