How to Get the First Element of a Set in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 05 20212 min read

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

In the code snippet, we used destructuring assignment to get the first element of the set and assign it to a variable.

An easy way to think about it is - we are assigning the 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

In the code snippet, we skip the first element by adding a , 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 into 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 the set into an array and use the index to access the element at position 0.

Converting the set into 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

In the code snippet we call the values method on the set to get an iterator.

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

Finally, we access 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. Don't get into the implementation details of sets in JavaScript, unless you have to.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee