0

If i have an object:

{
   a: "a",
   b: "b",
   c: "c",
}

and another object:

{
   b: "b",
   a: "a",
   c: "c",
}

does js guarantee that the ordering of the two will be the same when I iterate over them?

Object.values(firstObject).forEach(console.log) // a, b, c
Object.values(secondObject).forEach(console.log) // a, b, c
jmargolisvt
  • 4,749
  • 4
  • 23
  • 36
Dylan Kerler
  • 1,177
  • 3
  • 13
  • 3
    Try and find out? Generally speaking the order of keys in an object are not guaranteed. And shouldn't be an issue, as the hashing of the keys makes them quickly accessable. If you need to force an order, you need an array of some form. – Taplar Nov 03 '20 at 16:30
  • 3
    This is more a generic javascript question rather than specific to Nodejs. – Technoh Nov 03 '20 at 16:31
  • 1
    @Technoh I would kinda disagree there. One could say that potentially Firefox might do it differently, IE might do it differently, and the V8 engine might do it differently. By asking how node does it, the question is limiting scope. – Taplar Nov 03 '20 at 16:33
  • @Technoh Not really since different standards have different guarantees. I want to know if the version that nodejs implements has an ordering guarantee. I'm not talking about preserving the original insertion ordering - just if there is a deterministic algo that calculates how the ordering should be (obviously omitting the values and only taking the keys into account). – Dylan Kerler Nov 03 '20 at 16:34
  • 2
    @DylanKerler Yes, there is, the algo does preserve creation order (for non-integer keys). Since all engines did this and having a deterministic algorithm is useful to avoid incompatibilities, it got standardised. – Bergi Nov 03 '20 at 16:43
  • ^ Meaning that `Object.values(secondObject)` should return `["b", "a", "c"]` if it is defined as `{b: "b", a: "a", c: "c"}`. So either the definition of the second object or the output of the second object is incorrect. – 3limin4t0r Nov 03 '20 at 16:50

0 Answers0