Question
If I create an object like this:
var obj = {};
obj.prop1 = "Foo";
obj.prop2 = "Bar";
Will the resulting object always look like this?
{ prop1 : "Foo", prop2 : "Bar" }
That is, will the properties be in the same order that I added them?
Answer
The iteration order for objects follows a certain set of rules since ES2015, but it does not (always) follow the insertion order. Simply put, the iteration order is a combination of the insertion order for strings keys, and ascending order for number-like keys:
// key order: 1, foo, bar
const obj = { "foo": "foo", "1": "1", "bar": "bar" }
Using an array or a [Map
object](https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Map) can be a better way to
achieve this. Map
shares some similarities with Object
and [guarantees the
keys to be iterated in order of insertion](https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Map#Objects_and_maps_compared),
without exception:
The keys in Map are ordered while keys added to object are not. Thus, when iterating over it, a Map object returns keys in order of insertion. (Note that in the ECMAScript 2015 spec objects do preserve creation order for string and Symbol keys, so traversal of an object with ie only string keys would yield keys in order of insertion)
As a note, properties order in objects weren’t guaranteed at all before ES2015. Definition of an Object from [ECMAScript Third Edition (pdf)](http://www.ecma-international.org/publications/files/ECMA-ST- ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf):
4.3.3 Object
An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.