How to Get the First Element of a Set in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Get the First Element of a Set in JavaScript #

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.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.