JavaScript objects are dynamic.
And so we can insert any property into it at any time.
In this article, we’ll see if JavaScript objects have a guaranteed order for sorting properties.
ES2015 Objects
In ES2015, the order mostly follows the insertion order.
This is true expect and some keys are numbers.
If there’s a mix of numeric and non-numeric keys, then the numeric keys are traversed first.
Then the other keys are traversed.
The behavior for numeric keys can vary between browsers.
Chromium doesn’t respect the insertion order for numeric keys and put them first for example.
For instance, if we have the following object:
const obj = Object.create(null, {
m: {
value() {},
enumerable: true
},
"2": {
value: "2",
enumerable: true
},
"b": {
value: "b",
enumerable: true
},
0: {
value: 0,
enumerable: true
},
[Symbol()]: {
value: "sym",
enumerable: true
},
"1": {
value: "1",
enumerable: true
},
"a": {
value: "a",
enumerable: true
},
});
for (const prop in obj) {
console.log(prop)
}
When we loop through it with the for-in loop, we see that we get:
0
1
2
m
b
a
logged.
The numeric keys came first.
Then the non-numeric string keys are loop through in their order that they’re inserted.
The following methods guarantee to traverse the keys in the order in that they’re inserted:
Object.assign
Object.defineProperties
Object.getOwnPropertyNames
Object.getOwnPropertySymbols
Reflect.ownKeys
But these methods or loops don’t guarantee to traverse objects in any order:
Object.keys
for..in
JSON.parse
JSON.stringify
However, we can sort the keys if we use Object.keys
since the keys are returned in an array.
Before ES2015
Before ES2015, the iteration order of object keys isn’t defined.
This means that they can vary between different runtime environments.
However, most of them follow the same rules as in ES2015.
Conclusion
There’s no guarantee that object properties are traversed in any order in JavaScript objects.
Therefore, we should sort them or use JavaScript maps if we want to guarantee that keys are traversed in the order we want.