Open In App
Related Articles

How are elements ordered in a Set in JavaScript ?

Improve Article
Improve
Save Article
Save
Like Article
Like

In JavaScript, a new object called Set was introduced in the ES6 version. The Set object is similar to Map but the major difference is that elements in the set are unique and repeated addition of the same type of elements is not possible. The set can store any type of value whether primitive or objects. The elements of a set are iterable. Elements are always iterated in the insertion order.

The elements of a set are ordered which means that they can be accessed/iterated in the order of their insertion.

Syntax:

new Set([it]);

Example 1: In this example, we will create a basic set object and iterate over its elements to see the order.

Javascript




let sample = new Set();
sample.add("Hello");
sample.add("Geek");
sample.add("How");
sample.add("Are");
sample.add("You")
let data = sample.values();
for(let val of data) {
    console.log(val);
}


Output:

Hello
Geek
How
Are
You

Example 2: In this example, we will use an iterator to access the elements of Set and verify the order of elements.

Javascript




let sample = new Set();
sample.add("Hello");
sample.add("Geek");
sample.add("How");
sample.add("Are");
sample.add("You")
 
let getit = sample[Symbol.iterator]();
console.log(getit.next());
console.log(getit.next());
console.log(getit.next());
console.log(getit.next());
console.log(getit.next());


Output:

{value: 'Hello', done: false}
{value: 'Geek', done: false}
{value: 'How', done: false}
{value: 'Are', done: false}
{value: 'You', done: false}

Explanation: We can easily verify that the elements in the set follow the same order in which they are inserted.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 22 May, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials