Title : How to Get the First Element of a Set in JavaScript
1. Get the First Element of a Set in JavaScript Using Destructuring:
const set = new Set([1, 2, 3]);
const [first] = set;
console.log(first); // Output: 1
Explanation:
- Here, we create a new Set called setwith elements[1, 2, 3].
- We use array destructuring to extract the first element of the Set and assign it to the variable first.
- 
console.log(first)prints the value of the variablefirst, which is the first element of the Set.
2. Get the First Element of a Set in JavaScript Using Spread Syntax (...):
const set = new Set([1, 2, 3]);
const firstElement = [...set][0];
console.log(firstElement); // Output: 1
Explanation:
- 
[...set]spreads the elements of the Set into an array.
- 
[0]accesses the first element of the resulting array.
- 
console.log(firstElement)prints the value of the variablefirstElement, which is the first element of the Set.
3. Get the First Element of a Set in JavaScript Using Set.values():
const set = new Set([1, 2, 3]);
const firstElement = set.values().next().value;
console.log(firstElement); // Output: 1
Explanation:
- 
set.values()returns an iterator object containing the values of the Set in insertion order.
- 
.next()method is used to advance the iterator.
- 
.valueretrieves the value of the current element in the iteration.
- 
console.log(firstElement)prints the value of the variablefirstElement, which is the first element of the Set.
4. Get the First Element of a Set in JavaScript Using for...of Loop:
const set = new Set([1, 2, 3]);
let firstElement;
for (const element of set) {
    firstElement = element;
    break;
}
console.log(firstElement); // Output: 1
Explanation:
- 
for...ofloop iterates over the elements of the Set.
- Inside the loop, we assign each element to the variable firstElement.
- 
breakstatement is used to exit the loop after processing the first element.
- 
console.log(firstElement)prints the value of the variablefirstElement, which is the first element of the Set.
Each of these methods achieves the same result, which is obtaining the first element of the Set.
 

 
    
Top comments (0)