Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Interesting Facts about JavaScript Arrays
Next article icon

Interesting Facts about JavaScript Set

Last Updated : 13 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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);  

Output
Set(3) { 1, 2, 3 } 

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);  

Output
2 

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]); 

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); } 

Output
1 2 3 4 

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); } 

Output
30 20 10 

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));   

Output
true false 

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);   

Output
Set(3) { 1, 3, 4 } 

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);   

Output
[ 1, 2, 3, 4, 5 ] 

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;   

Output
true 

Next Article
Interesting Facts about JavaScript Arrays

M

meetahaloyx4
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Set

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 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 Data Types
    JavaScript (often abbreviated as JS) is one of the most popular programming languages in the world. It comes with its unique take on data types that sets it apart from languages like C, C++, Java, or Python. Understanding how JavaScript handles data types will be very interesting, which can help you
    6 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 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
  • JavaScript Set() Constructor
    The Javascript Set constructor is used to create Set objects. It will create a set of unique values of any type, whether primitive values or object preferences. It returns the new Set object. It mainly helps in creating a new set of objects which contains unique elements. Syntax:new Set()new Set(ite
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences