Sunday, June 14, 2026
HomeLanguagesJavascriptHow are elements ordered in a Set in JavaScript ?

How are elements ordered in a Set in JavaScript ?

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, neveropen 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!
RELATED ARTICLES

4 COMMENTS

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS