1console.log("hello-world);
javascript
console.log("hello-world);
hidden codeblock for CSS
css
.container {
  width: 80%;
}
hidden codeblock for CSS
html
<pre><code class="language-css">
.container {
  width: 80%;
}
</code></pre>
hidden codeblock for CSS
1console.log("hello-world);
javascript
console.log("hello-world);
hidden codeblock for CSS
css
.container {
  width: 80%;
}
hidden codeblock for CSS
html
<pre><code class="language-css">
.container {
  width: 80%;
}
</code></pre>
hidden codeblock for CSS

4 Ways To Get The First Element Of A Set In JavaScript

ReadTime: 4 minutes

Sets in JavaScript provide a unique collection of values with no duplicates. When working with Sets in JavaScript, efficiently accessing the first element is crucial. Let’s explore the various methods to do so: Destructuring, Spread Syntax, Set.values(), and for...of loop.


Using Destructuring Assignment

Destructuring assignment allows for a concise method of obtaining the first element of a Set. By employing a simple syntax like const [first] = set, we can quickly access and utilize the initial element.

javascript
const set = new Set([1, 2, 3]);
const [first] = set;
console.log(first); // Output: 1
destructuring to extract first element of a set

This method ensures a clean and readable way of retrieving the first Set element.


Bonus: Getting the Second Element of a Set

Extending this approach, we can adapt the destructuring assignment to access subsequent elements by introducing a comma , to denote positions.

javascript
const set = new Set([1, 2, 3]);
const [, second] = set;
console.log(second); // Output: 2
Getting second element of set

Using Spread Syntax

Spread syntax provides an alternative by converting the Set to an array and extracting the first element.

javascript
const set = new Set([1, 2, 3]);
const first = [...set][0];
console.log(first); // Output: 1
spread syntax to extract first element

Insights:

  • While effective, this method might be less efficient for larger Sets due to the array conversion process. O(n) task, where n is length of Set.

Using Set.values()

For a more structured approach, the Set.values() method proves useful. This involves a three-step process:

  1. Use Set.values() to get an iterable of Set values.
  2. Utilize next() to obtain an object with the first value.
  3. Assign the value to a variable.
javascript
const set = new Set([1, 2, 3]);
const values = set.values();
const obj = values.next();
const first = obj.value;
console.log(first); // Output: 1
Set.values() and next() to extract first value of a set

Insights:

  • This method introduces more steps, impacting readability.

Using for…of Loop

A for…of loop offers a straightforward means of extracting the first element of a Set. This loop iterates over the Set, assigning the first value to a variable.

javascript
const set = new Set(['apple', 'banana', 'orange']);
let first;

for (const element of set) {
  first = element;
  break;
}

console.log(first); // Output: apple
for...of loop to exrtact first element of set

Insights:

  • While simple, this method lacks the directness of other approaches and involves explicit looping.

Practice Problem

Now, let’s solidify your understanding with a practice coding question.

You are given an array of student names. Create a JavaScript function named getFirstStudent that takes this array and returns the first student’s name.

Problem (JavaScript)

javascript
function getFirstStudent(studentNames) {
  // > > > 👉 Write code here 👈 < < <
}

// Example Usage:
const students = ['Alice', 'Bob', 'Charlie', 'David'];
const firstStudent = getFirstStudent(students);
console.log(firstStudent);
// Expected Output: 👇
// Alice
Problem Code

Please attempt before seeing the Answer:

Solution
javascript
// Solution uses simple array indexing to directly access the first element.
// For efficiency and clarity.

function getFirstStudent(studentNames) {
  let firstStudent;

  for (const student of studentNames) {
      firstStudent = student;
      break;
  }

  return firstStudent;
}
Solution Code

Conclusion:

So, you found multiple ways of retrieving first element of Set in Javascript? But remember, coding is not just about finding a solution; it’s about finding the right solution for the task at hand. Happy coding! 🚀

Contact

Feel free to reach out!