Open In App

How are elements ordered in a Set in JavaScript ?

Last Updated : 22 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads