0

I recently came across a bug on a project due to a quirky behavior of Javascript.

Consider the following operations:

let a = {}
a['foo'] = "this"
a['bas'] = "that"
a['bar'] = "meh"

let b = {}
b[1] = "this"
b[3] = "that"
b[2] = "meh"

let c = {}
c[' ' + 1] = "this"
c[' ' + 3] = "that"
c[' ' + 2] = "meh"

let d = {}
d[1 + ''] = "this"
d[3 + ''] = "that"
d[2 + ''] = "meh"

console.log(a, b, c, d)

If you notice, a and c had the keys in the exact same fashion that they were assigned to the objects, however, b and d appear to have the keys sorted in ascending order.

Any ideas why?

Paulo
  • 325
  • 3
  • 16
  • 1
    *"Any ideas why?"* Because property order is not defined in the spec, so browsers did it one way or the other. The order used to differ between browsers, now there are more or less aligned. You should have never relied on property order in the first place. – Felix Kling Jun 05 '18 at 07:25
  • Your question is marked as duplicated so I can not completely answer your question. But my answer is in clear and simple way to check the `==` operation. `'1' == 1 // true` and `' ' + 1 == 1 // false`. The order based on this. – Sakata Gintoki Jun 05 '18 at 07:43
  • @SakataGintoki, keys of objects, as well as arrays are strings. – Nina Scholz Jun 05 '18 at 07:45
  • @NinaScholz Yes, the key will be used to compare with index number, if the result is `true`, the key will be used as number even it is a string. `' 1' ` (included space) is completely string, but `'1'` is not. – Sakata Gintoki Jun 05 '18 at 07:58

0 Answers0