How to add to a Set in JavaScript

Adding values to JavaScript Sets is fundamental for building dynamic collections of unique elements during runtime. With over 25 years of experience in software development and as the creator of CoreUI, I’ve used Set addition operations extensively in UI component state management and data processing. From my expertise, the most straightforward approach is using the add() method which automatically ensures uniqueness and maintains insertion order. This method provides efficient collection building while preventing duplicate entries.

Use the add() method to insert new values into a Set while maintaining uniqueness automatically.

const mySet = new Set()
mySet.add('apple')
mySet.add('banana')
mySet.add('apple') // Duplicate - won't be added
console.log(mySet) // Set(2) { 'apple', 'banana' }

Here mySet.add('apple') adds the value ‘apple’ to the Set. When adding ‘apple’ again, the Set ignores the duplicate since it already contains that value. The add() method returns the Set itself, allowing for method chaining like mySet.add('apple').add('banana').add('orange'). Sets automatically handle uniqueness comparison, so each value appears only once regardless of how many times it’s added.

Best Practice Note:

This is the same approach we use in CoreUI components for building collections of active states, selected items, and unique identifiers. The add method is chainable, making it perfect for fluent interfaces and building Sets programmatically in loops or method chains.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team