Last updated: Mar 1, 2024
Reading timeยท3 min

Set.values()for...ofUse destructuring assignment to get the first element of a Set, e.g.
const [first] = set.
The destructuring assignment sets the variable to the first element of the Set.
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 then we assigned it to a variable.
Set element at position 1 to the variable named first.We can get the second element of the Set in a similar way.
const set = new Set([1, 2, 3]); const [, second] = set; console.log(second); // ๐๏ธ 2

We skipped the first element by adding a comma , to 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.
The spread syntax converts an array-like object to an array.
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.
Set.A more long-winded way is to use the methods on the Set instance.
Set.values()This is a three-step process:
Set.values() method to get an iterable of the values in the Set.next() method to get an object containing the first value of the
iterable.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 iterable of
the values in the Set.
We then called the next() method on the iterable 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.
for...ofYou can also use a for...of loop to get the first element of a Set.
const set = new Set(['bobby', 'hadz', 'com']); let first; for (const element of set) { first = element; break; } console.log(first); // ๐๏ธ bobby

We declared the first variable using the let keyword.
This is important because variables declared using const cannot be reassigned.
We used a for...of loop to
iterate over the Set for a
single iteration.
The for...of statement is
used to loop over iterable objects like arrays, strings, Map, Set and
NodeList objects and generators.
Once we assign the first value of the Set to a variable, we exit the
for...of loop.
The
break
statement terminates the current loop or switch statement.