How does a JavaScript object sort itself in ascending order of keys?
This is a new discovery for me.
/* Yes, it maintains an order. The order is based on the sequence of insertion. If there are no specific orders being maintained, please provide an example to help clarify the concept for me.
Thanks in advance.
*/
var a = {"13" : "1", "15" : "2", "14" : "3", "12" : "4"};
console.log(JSON.stringify(a)); /* This is not related to any for loop */
for(let i in a) {
console.log(i + " = " + a[i]);
}
/* However, keys that are not numbers are not sorted. */
var b = {"c" : "1", "a" : "2", "b" : "3", "d" : "4"};
for(let i in b) {
console.log(i + " = " + b[i]);
}
The first object organizes itself by default. I am using string keys for both objects. Surprisingly, the second object does not sort alphabetically as expected.