Set
A collection of unique values: each value can appear in the set only once.
- Returns
- A new
Setobject.
Example
#const badges = new Set()
badges.add('First lesson').add('7-day streak')
badges.add('First lesson')
console.log(badges.size)
console.log(badges.has('7-day streak'))
console.log(badges)Definition and usage
#Set is a collection that stores values without duplicates. Adding a value that’s already in the set changes nothing. Values are compared similarly to === (except that NaN equals NaN), so two separate objects with the same content count as two different values.
The add(), has(), delete(), and clear() methods let you add, check, and remove elements, and the size property returns their count. Checking with has() is very fast even with thousands of elements, unlike includes() on a large array.
The most common use is removing duplicates from an array: [...new Set(array)]. A set is also handy for tracking visited lessons, selected elements, or earned badges.
Since 2024, browsers have also had set operation methods: union(), intersection(), difference(), and isSubsetOf() for checking containment.
Syntax
#new Set()
new Set(iterable)
set.add(value)
set.has(value)
set.delete(value)
set.clear()
set.sizeParameters
#iterable
optional
An array or other iterable. Its values go into the set, without duplicates.
More examples
#const tags = ['html', 'css', 'html', 'js', 'css']
const unique = [...new Set(tags)]
console.log(unique)const emma = new Set(['HTML', 'CSS', 'JS'])
const jack = new Set(['CSS', 'Python'])
console.log(emma.union(jack))
console.log(emma.intersection(jack))
console.log(emma.difference(jack))The union(), intersection(), and difference() methods work in browsers released since 2024. In older ones, you need to replace them with array filtering.
const selected = new Set()
const lesson = { id: 1 }
selected.add(lesson)
selected.add(lesson)
selected.add({ id: 1 })
console.log(selected.size)Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- You can get an array’s unique values in a single line:
[...new Set(array)]. - When you frequently check whether a value is in a list, convert the array to a
Setand usehas(). For large data sets, this is much faster. - A set has no indexes or
map()/filter()methods. To use those, convert it to an array:[...set].
Related entries
#- MapA collection of key-value pairs where the key can be any value and insertion order is preserved.
- Array.from()Creates an array from an iterable or "array-like" object.
- Array.prototype.includes()Checks whether an array contains the given value.
- Spread (...)The spread syntax spreads an array, string, or object out into individual elements: for copying, merging, and passing arguments.
- for...ofWalks the successive values of an iterable object: an array, a string, a Map, a Set, and others.
Spotted a mistake or missing an example? Write to us.