Sets

BrandonDusch's avatar
Published Dec 30, 2021Updated Jun 16, 2022
Contribute to Docs

A Set is an object in JavaScript that is a collection of unique values.

Syntax

const mySet = new Set();

A Set object can be created with the Set() constructor function.

Initializing With Iterable Objects

Sets can also be created with iterators passed to the Set() constructor, as shown below:

const newSet = new Set([2, true, 2, 'some string', { name: 'John' }]);
console.log(newSet);
console.log(newSet.size);

The output will look like this:

Set(4) { 2, true, 'some string', { name: 'John' } }
4

Codebyte Example

An interesting usage of Set is that we can use it to filter out duplicate values from an array:

Code
Output
Loading...

Sets

.add()
Inserts a value into a Set (if it is unique) and returns the updated Set object.
.clear()
Deletes all values from a Set and returns undefined.
.delete()
Removes the specified value from the Set and returns a boolean indicating whether or not the deletion was successful.
.has()
Checks whether a value exists in a given Set and returns either true or false.
.size
Returns the number of values in a Set.

All contributors

Contribute to Docs

Learn JavaScript on Codecademy