- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Creating a Set using Javascript
Let's create a MySet class so that it doesn't hide the actual set class in JS. We'll create a container object that'll keep track of all our values that we add to the set. We'll also create a display function that prints the set for us.
Example
class MySet { constructor() { this.container = {}; } display() { console.log(this.container); } }
In ES6, you can directly create a set using the Set class. For example,
Example
const set1 = new Set(); const set2 = new Set([1, 2, 5, 6]);
Checking for membership
The has method checks if a value exists in the set or not. We'll use the Object.hasOwnProperty method to check it in the container. For example,
Example
has(val) { return this.container.hasOwnProperty(val); }
In ES6 Sets, you can use this directly −
Example
const testSet = new Set([1, 2, 5, 6]); console.log(testSet.has(5)); console.log(testSet.has(20)); console.log(testSet.has(1));
Output
This will give the output −
True False True
- Related Articles
- Creating a BinaryTree using Javascript
- Creating a Priority Queue using Javascript
- Creating a linked list using Javascript
- Creating a hash table using Javascript
- Creating Arrays using Javascript
- Creating Dictionary using Javascript
- Creating a Doubly Linked List using Javascript
- Creating a Simple Calculator using HTML, CSS, and JavaScript
- Creating a Sorted Set in Java
- Creating JavaScript constructor using the “new” operator?
- Creating auto-resize text area using JavaScript
- Creating a Dynamic Report Card using HTML, CSS, and JavaScript
- Loop through a Set using Javascript
- Creating Animated Counter using HTML, CSS, and JavaScript
- Creating a Stack in Javascript

Advertisements