Open In App

Is set Ordered in JavaScript ?

Yes, the order of elements in a Set is guaranteed to be the same as the order of insertion. This means that when you iterate over the elements of a Set using methods like forEach or the for...of loop, the elements will be returned in the order in which they were added to the Set.

Example: Here, the elements were added to the Set in the order 3, 1, 2. When iterating over the Set using forEach, the elements are returned in the same order.




// Creating a Set
const mySet = new Set();
 
// Adding values to the Set in a specific order
mySet.add(3);
mySet.add(1);
mySet.add(2);
 
// Iterating through the Set
mySet.forEach(value => {
  console.log(value);
});

Output
3
1
2
Article Tags :