0
const CONSTANT = Object.freeze({a: 1, b: 2});

Is it guaranteed that Object.values(CONSTANT) will return [1, 2]?

On MDN's doc, it says it follows for...in which iterates in in original insertion order.

On some SO answers, it claims order is guaranteed for getOwnPropertyNames but not for...in.

Also, what implementation could they use to guarantee insertion order? If a sorted collection of some sort is used to track the order, wouldn't it result in O(log n) complexity for insertion/deletion of object properties?

Avery235
  • 3,198
  • 6
  • 32
  • 72
  • 1
    I think the bottom line here is: You are NOT guaranteed that the order will be [1,2], nor that it will it be the insertion order. It might be either [1,2] or [2,1], but you ARE guaranteed the order of `Object.values` will be the same as `for...in` and that it will not change, unless the object itself changes. – K. Kirsz Jul 21 '17 at 08:59
  • @K. Kirsz [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) says `The for...in statement iterates over the enumerable properties of an object, in original insertion order.` – Avery235 Jul 21 '17 at 09:02
  • MDN's statements are not canonical. –  Jul 21 '17 at 09:03
  • The question isn't specific to Object.values. This entirely depends on how object properties order is handled by JS engine. – Estus Flask Jul 21 '17 at 09:12

1 Answers1

0
for (let v of ['a','b']) {
    console.log(CONSTANT[v])
}

Would guarantee the order.

xlm
  • 4,594
  • 13
  • 42
  • 47
Yasin Bahtiyar
  • 2,117
  • 3
  • 17
  • 18
  • Well yes, if you use an array to control the iteration. The question is asking about iterating over the properties of an object directly. – James Thorpe Jul 21 '17 at 08:52