How to use JavaScript Set add() Method? [SOLVED]


JavaScript

In JavaScript, if you want a collection of unique values in a similar structure as an array, there is a special object that provides such functionality - the Set object. The Set object lets you store unique values of any type, whether primitive values or object references.

In this article, we will discuss how to create a Set object and how to add to a Set object.

 

All about the JavaScript Set Object

A Set is a collection of unique values. The values can be either primitive values or object references. The Set can be created using the new Set() constructor.

let mySet = new Set();
let theSet = new Set([1, 2, 3, 4, 44, 4, 5]);

console.log(mySet, theSet);

Output

Set(0) {} Set(6) { 1, 2, 3, 4, 44, 5 }

We can check if a Set object has an element, and access the elements within a Set object using the has and for loop.

console.log(theSet.has(1));
console.log(theSet.has(6));

for (let item of theSet) {
    console.log(item);
}

Output

true
false
1
2
3
4
44
5

Now, how can we add new elements to a Set object?

 

Use add to add to JavaScript Set

Adding an element to a Set in JavaScript can be done using the add() method. This method accepts a single parameter, which is the element to be added to the Set. The add() method will return the Set object, so it can be chained with other methods.

If there is already that element within the set, the element will not be added.

Let’s illustrate how to add elements to a JavaScript Set object

const xer = new Set([12, 3, 4, 5, 5, 3, 1]);

console.log(xer);

xer.add("wow");
xer.add(234);

console.log(xer);

Output

Set(5) { 12, 3, 4, 5, 1 }
Set(7) { 12, 3, 4, 5, 1, 'wow', 234 }

The elements wow and 234 have been added to the xer Set.

 

Summary

The JavaScript Set Object allows us to store unique values. To add new elements to the object, we can make use of the instance method, add.

 

References

Set - JavaScript | MDN (mozilla.org)
Set.prototype.add() - JavaScript | MDN (mozilla.org)

 

Olorunfemi Akinlua

Olorunfemi Akinlua

He is boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital experiences across various domains. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment