According to my prior knowledge, JavaScript objects are basically hash maps (hash tables) which means -> set and get are done in O(1)
Lately I came across this article - https://javascript.info/object which points out the following example:
let codes = {
"49": "Germany",
"41": "Switzerland",
"44": "Great Britain",
// ..,
"1": "USA"
}
for (let code in codes) {
console.log(code); // 1, 41, 44, 49
}
And the official MDN site:
const anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.entries(anObj)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ]
The explenation I came across is:
So what exactly is going on?
Here are the ordering rules: Numbers are ordered first, and they are ordered within themselves from smallest to largest as long as they are >=0 (see below for more details) Strings come second, and they are ordered within themselves by insertion order Symbols come last, and they are ordered within themselves by insertion order (note that we didn't use symbols in this example)
So I'm pretty confused here, and my question is:
When does the object keys ordering happens?
In case the object sort the keys itself, it means that the insert time is not O(1). Because every time I insert a new value, all the keys should be reordered.
The only case I think this behaviour could happens and keep the O(1) rule, is that the ordering happens only on display or in the use of Object.keys
function.
Anyone got an idea when does the ordering process happens?