How to Get the First Element of a Set in JavaScript

Borislav Hadzhiev

Last updated: Jul 25, 2022

Photo from Unsplash

**To get the first element of a Set, use destructuring assignment, e.g.
const [first] = set. The destructuring assignment sets the variable to the
first element of the Set.**

index.js

`const set = new Set([1, 2, 3]); const [first] = set; console.log(first); // 👉️ 1`

We used
destructuring assignment
to get the first element of the `Set`

and assigned it to a variable.

An easy way to think about it is that we're assigning the

`Set`

element at position `1`

to the variable named `first`

.We can get the second element of the `Set`

in a similar way:

index.js

`const set = new Set([1, 2, 3]); const [, second] = set; console.log(second); // 👉️ 2`

We skipped the first element by adding a comma `,`

to the denote the place of
the first element in the destructuring assignment.

We can also get the first element of a set using the spread syntax.

**To get the first element of a set, use the spread syntax to convert the Set to
an array and access the element at index 0, e.g.
const first = [...set][0].**

index.js

`const set = new Set([1, 2, 3]); const first = [...set][0]; console.log(first); // 👉️ 1`

We can iterate over a `Set`

, so we can also convert one to an array
to use the index to access the element at position `0`

.

Converting the set to an array would be very inefficient and slow if you have thousands of elements in the

`Set`

.A more long winded way to get the first element of a `Set`

is to use
the methods on the `Set`

instance.

index.js

`const set = new Set([1, 2, 3]); const values = set.values(); // 👉️ iterator const obj = values.next() // 👉️ {value: 1, done: false} const first = obj.value; console.log(first); // 👉️ 1`

We called the `values`

method on the `Set`

to get an iterator.

We then called the `next`

method on the iterator to get an object containing the
value of the first iteration.

Finally, we accessed the `value`

property on the object to get the value of the
first element in the `Set`

.

The first 2 approaches are definitely more readable and intuitive. It's best to not leak the implementation details of

`Set`

objects in your code.- How to Initialize a Set with Values in JavaScript
- Check if a Set contains a Value using JavaScript
- How to Check if two Sets are equal using JavaScript
- How to check if a Set is Empty in JavaScript
- How to sort a Set in JavaScript
- How to get the Length of a Set in JavaScript
- How to convert a Set to an Array in JavaScript
- How to Convert an Array to a Set in JavaScript
- Check if Object is of type Set in JavaScript