Set

A collection of unique values: each value can appear in the set only once.

Returns
A new Set object.
On this page

Example

#
JavaScript
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)
Console
2
true
Set(2) { 'First lesson', '7-day streak' }

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

#
Syntax
new Set()
new Set(iterable)

set.add(value)
set.has(value)
set.delete(value)
set.clear()
set.size

Parameters

#
  • iterable

    optional

    An array or other iterable. Its values go into the set, without duplicates.

More examples

#
Removing duplicates from an array
JavaScript
const tags = ['html', 'css', 'html', 'js', 'css']
const unique = [...new Set(tags)]

console.log(unique)
Console
['html', 'css', 'js']
Set operations
JavaScript
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))
Console
Set(4) { 'HTML', 'CSS', 'JS', 'Python' }
Set(1) { 'CSS' }
Set(2) { 'HTML', 'JS' }

The union(), intersection(), and difference() methods work in browsers released since 2024. In older ones, you need to replace them with array filtering.

Objects compared by reference
JavaScript
const selected = new Set()
const lesson = { id: 1 }

selected.add(lesson)
selected.add(lesson)
selected.add({ id: 1 })

console.log(selected.size)
Console
2

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 Set and use has(). 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

#

Spotted a mistake or missing an example? Write to us.