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:
Applications of Set in JavaScript
Next article icon

Internal Working of Set in JavaScript

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

JavaScript Set is a collection of unique values, i.e. values can not be repeated. The values can be primitive or objects. ES6 sets are ordered according to the insertion order. In this article, we will check the internal working of a set in Javascript.

Working of Set

Sets in JavaScript internally use Hash Table which means the operations like search, insert and delete work in constant or O(1) time on average and all the stored items are unique.

It uses value equality to determine uniqueness, comparing values based on their data type. Iteration is predictable since the values' insertion sequence is retained. The Set data structure simplifies managing unique values in JavaScript applications.

In order to check the performance of a set we compare it with the includes() method of the array and generally it is found to be faster than the includes() method.

Example: Here is the basic example of a JavaScript set.

JavaScript
let s = new Set([10, 20, 30, 30, 40, 40]);  for (const item of s) {     console.log(item); } 


Set(4) {10, 20, 30, 40}Output: We can see the elements in the set are stored in the same order as they are defined and the value equality algorithm removes the duplicates before storing the data in the set.Output: We can see the elements in the set are stored in the same order as they are defined and the value equality algorithm removes the duplicates before storing the data in the set.

Example 2: This example describes the uses of Set Object in JavaScript.

JavaScript
const setVal = new Set();  for (let i = 0; i < 1000000; i++) {     setVal.add(i); }  const arr = Array.from(Array(1000000), (_, i) => i); let include = arr.includes(999999)  console.time('set') console.log(setVal.has(999999)); // Output: true console.timeEnd('set')  console.time('Array') console.log(arr.includes(999999)); // Output: true console.timeEnd('Array') 

Output: In this example, we compared has() method with the includes() method of the array. The set has() method takes less time than the includes() method of the array.

true
set: 0.126220703125 ms
true
Array: 0.48388671875 ms

Importance of Set:

  • Handling Collections: To handle collections of elements, such as eliminating duplicates from an array, use the set function. You may quickly get rid of duplicate elements by changing an array to a Set and back again.
  • Unique Values: A Set is mostly used to store distinctive values. By preventing duplicate values, it makes sure that each element in the set is distinct. For situations when you need to save a collection of unique values, Set is perfect.
  • Iteration: A Set is iterable, which means you can easily loop through its elements using for...of loops or by using methods such as forEach(). This makes it convenient to iterate over the unique values stored in a Set and perform operations on them.
  • Mathematical Set Operations: Set enables a variety of set operations in mathematics, including union, intersection, and difference. Using methods like add(), remove(), and forEach(), you can quickly carry out similar operations on Set objects.
  • Memory Efficiency:  Compared to other methods, such as manually looking for duplicates in an array or object, utilizing a Set can be more memory-efficient in situations when you have a big collection of data and want to assure their uniqueness.

Next Article
Applications of Set in JavaScript

V

vishalkumar2204
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions
  • JavaScript-Set

Similar Reads

  • Iterate over Set in JavaScript or JS
    We will iterate over set elements in JavaScript. A set is a collection of unique elements i.e. no element can appear more than once in a set. Below are the approaches to iterate over set elements in JavaScript: Approach 1: Using for...of loopThe for…of loop iterates over the iterable objects (like A
    3 min read
  • How to perform intersection of two sets in JavaScript ?
    An intersection of two sets means the element which occurs in both sets. In mathematical terms, the intersection of two sets is shown by A ∩ B. It means all the elements which is common in set A and set B should occur in a single array. In javascript, the intersection of two sets means getting the c
    2 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
  • Nesting For Loops in JavaScript
    Nesting for loops is crucial in JavaScript, enabling iteration over multi-dimensional data structures or performing complex tasks. It involves placing one loop inside another, where the outer loop executes for each iteration of the inner loop. This facilitates operations on multi-dimensional arrays
    4 min read
  • Set to Array in JS or JavaScript
    This article will show you how to convert a Set to an Array in JavaScript. A set can be converted to an array in JavaScript in the following ways: 1. Using Spread OperatorThe JavaScript Spread Operator can be used to destructure the elements of the array and then assign them to a new variable in the
    2 min read
  • JavaScript in Operator
    JavaScript in operator is an inbuilt operator which is used to check whether a particular property exists in an object or not. It returns a boolean value true if the specified property is in an object, otherwise, it returns false. Syntax:prop in objectParameters: prop: This parameter holds the strin
    2 min read
  • JavaScript in and instanceof operators
    JavaScript Relational Operators are used to compare their operands and determine the relationship between them. They return a Boolean value (true or false) based on the comparison result. JavaScript in OperatorThe in-operator in JavaScript checks if a specified property exists in an object or if an
    3 min read
  • Set in JavaScript
    A Set in JavaScript is used to store a unique collection of items, meaning no duplicates are allowed. Sets internally use a hash table which makes search, insert and delete operations faster than arrays. Please note that a hash table data structure allows these operations to be performed on average
    4 min read
  • How to get the union of two sets in JavaScript ?
    A union set is the combination of two elements. In mathematical terms, the union of two sets is shown by A ∪ B. It means all the elements in set A and set B should occur in a single array. In JavaScript, a union set means adding one set element to the other set. Set automatically take care of the un
    2 min read
  • JavaScript Instanceof Operator
    The instanceof operator in JavaScript is used to check the type of an object at run time. It returns a boolean value if true then it indicates that the object is an instance of a particular class and if false then it is not.  Syntax:let gfg = objectName instanceof objectTypeParameters: objectName: S
    2 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