Is Set in JavaScript guaranteed to be stable?

Viewed 164

Playing with Set, it appears to be stable (ie items remain in the order they are seen in):

> [...new Set(["foo", "bar", "foo", "foo", "baz", "bar"])]
["foo", "bar", "baz"]

But I can't find any documentation that says it is guaranteed to be stable.

2 Answers

According to MDN you can iterate through the elements of a set in insertion order. The detailed documentation page of Set methods is full of "in insertion order" statements.

A test:

a = new Set()
a.add(1)
a.add(2)
a.add(4)
a.add(3)
console.log([...a]) // [1,2,4,3]

a.add(2) // already present element has no effect on order
console.log([...a]) // [1,2,4,3]

The ECMAScript® 2021 Language Specification says that Set(interable) will call .add for each item as the iterable returns them. The .add method says it will append items that don't exist. So the stability of Set is dependent on the stability of the iterable used. I am out of tuits and am willing to take it as read that an the iterator for arrays is stable (because if it isn't everything would break), but if someone pushes the guarantee further, I'll move the accepted flag to that answer.

Related