- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Add elements to a Set using Javascript
The add method checks if a value already exists in the set, if not, then it adds that value to the set. We can implement it as follows −
Example
add(val) { if (!this.has(val)) { this.container[val] = val; return true; } return false; }
You can test this using −
Example
const testSet = new MySet(); testSet.add(1); testSet.add(2); testSet.add(5); testSet.add(2); testSet.display(); console.log(testSet.has(5)); console.log(testSet.has(20)); console.log(testSet.has(1));
Output
This will give the output −
{ '1': 1, '2': 2, '5': 5 } True False True
Note that even though we tried adding 2 twice, it only got added once. If you try logging it, you'll get a false. This is because of the values we're returning if we don't add it.
In ES6, you use the add function as follows −
Example
const testSet = new MySet(); testSet.add(1); testSet.add(2); testSet.add(5); testSet.add(2); 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
- Add elements to a Queue using Javascript
- Add elements to a PriorityQueue using Javascript
- Add elements to a linked list using Javascript
- Add elements to a hash table using Javascript
- Remove elements from a Set using Javascript
- How to add HTML elements dynamically using JavaScript?
- Add elements to a Dictionary in Javascript
- Can we add null elements to a Set in Java?
- Creating a Set using Javascript
- Is it possible to add a set of elements in one cell with MySQL?
- How to remove all the elements from a set in javascript?
- How to add rows to a table using JavaScript DOM?
- How to add the previous set of elements on the stack to the current set in jQuery?
- Initialize a Set without using add() method in Java
- Java Program to add and remove elements from a set which maintains the insertion order

Advertisements