Interesting Facts about JavaScript Set
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
- Even though +0 and -0 are different values in terms of sign, they are treated as equal
- NaN is considered equal to itself in Set, which is different from how regular equality (===) works in JavaScript, where NaN !== NaN.
JavaScript
// 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]);
Output1
[ 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]);
Output2
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);
OutputSet(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;
Similar Reads
Interesting Facts About JavaScript
JavaScript (often abbreviated as JS) is one of the most popular programming languages in the world. It is an interpreted, high-level programming language that follows ECMAScript. It powers interactive websites and is packed with amazing features that make it special and powerful. Here are some inter
5 min read
Interesting Facts About JavaScript Strings
Let's see some interesting facts about JavaScript strings that can help you become an efficient programmer. Strings are ImmutableIn JavaScript, strings are immutable, which means once you create a string, you cannot change its characters individually. Any operation that appears to modify a string, l
3 min read
Interesting Facts about Object in JavaScript
Let's see some interesting facts about JavaScript Objects that can help you become an efficient programmer. JavaSctipt Objects internally uses Hashing that makes time complexities of operations like search, insert and delete constant or O(1) on average. It is useful for operations like counting freq
4 min read
Interesting Facts About Map in JavaScript
JavaScript Map is used to store the data of key-value pairs. It can be used to store any type of value including objects and primitive data types. It is iterable which is the main reason we can manipulate it according to the need. Map Internally Uses Hash TableJavaSctipt Map internally uses Hashing
5 min read
Interesting Facts about JavaScript Arrays
Let us talk about some interesting facts about JavaScript Arrays that can make you an efficient programmer. Arrays are ObjectsJavaScript arrays are actually specialized objects, with indexed keys and special properties. They have a length property and are technically instances of the Array construct
3 min read
Interesting Facts about JavaScript Functions
Let us talk about some interesting facts about JavaScript Functions that can make you an efficient programmer. Functions Are First-Class CitizensJavaScript treats functions as first-class citizens, meaning they can be: Stored in variablesPassed as arguments to other functionsReturned from other func
4 min read
Interesting Code Snippets in JavaScript
JavaScript is a flexible and powerful programming language that can solve problems in clever and simple ways. Here are some fun JavaScript code snippets that highlight its features and quirks. Whether you're a beginner or an experienced developer, these examples will spark your interest. 1. Flatteni
5 min read
Applications of Set in JavaScript
A Set is a collection of items that are unique i.e. no element can be repeated. Set in ES6 are ordered: elements of the set can be iterated in the insertion order. The set can store any type of value whether primitive or objects. Application of Set in JavaScript:Deleting duplicates element from an a
3 min read
Introduction to Built-in Data Structures in JavaScript
JavaScript (JS) is the most popular lightweight, interpreted compiled programming language, and might be your first preference for Client-side as well as Server-side developments. Let's see what inbuilt data structures JavaScript offers us: Data Structure Internal Implementation Static or Dynamic Ja
2 min read
Compact Objects in JavaScript
Compacting an object refers to removing properties with false values (like null, undefined, 0, false, "", NaN, etc.). Objects are used to store collections of data and more complex entities. They can be extended and manipulated in various ways to suit different programming needs. One interesting asp
3 min read