1

Recently I cam across an interesting scenario while working with javaScript objects.

If we add any strings in an object it gets saved in the order that we added them

let obj = {};
obj[“z”] = true;
obj[“a”] = true;
obj[“c”] = true;

console.log(Object.keys(obj)) // [“z”,”a”,”c”]

But in the case of adding numbers, it seems to sort it by default

let obj = {};
obj[9] = true;
obj[1] = true;
obj[5] = true;

console.log(Object.keys(obj)) // [1,5,9]

What is the reason that this is happening???

Sarath P S
  • 131
  • 5
  • 2
    Here is a chapter describing how it was implemented: https://exploringjs.com/es6/ch_oop-besides-classes.html#_traversal-order-of-properties "First, the string keys that are integer indices (what these are is explained in the next section), in ascending numeric order.". As for why, no clue! – Edon Mar 07 '20 at 03:16
  • Also, take a look at this answer in regards to ES2015 - https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order/38218582#38218582 – vivalldi Mar 07 '20 at 04:40
  • Does this answer your question? [Does JavaScript Guarantee Object Property Order?](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – vivalldi Mar 07 '20 at 04:41

0 Answers0