Do JavaScript Sets Preserve Insertion Order?

When you iterate over the elements of a Set using the Set.prototype.forEach() method or the for...of loop, each element of the Set is visited in the order in which it was added to the Set. This is true when you add an item to the Set in either of the following ways:

  1. Using the Set.prototype.add() method, or;
  2. Using the Set() constructor.

For example:

const mySet = new Set();

mySet.add(1);
mySet.add(2);
mySet.add(3);
mySet.add(3);

mySet.forEach((value) => {
  console.log(value);
});
const mySet = new Set([ 1, 2, 3, 3 ]);

mySet.forEach((value) => {
  console.log(value);
});

In both cases, the output will be the following:

1
2
3

The insertion order of the elements is maintained in these cases because the Set.prototype.forEach() method follows the ECMAScript specification, which states that the callback of Set.prototype.forEach() method should be called once for each element, in insertion order.

On the other hand, the for...of loop iterates over Sets in insertion order by automatically calling the Set.prototype[@@iterator]() method to obtain the Set iterator object, which yields the values of the Set in insertion order.

The examples from earlier can be rewritten using the for...of loop as follows:

const mySet = new Set();

mySet.add(1);
mySet.add(2);
mySet.add(3);
mySet.add(3);

for (const value of mySet) {
  console.log(value);
}
const mySet = new Set([ 1, 2, 3, 3 ]);

for (const value of mySet) {
  console.log(value);
}

Similar to the previous examples, this will produce the following output, eliminating duplicates and following insertion order:

1
2
3

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.