Default javascript object sorting across browsers


by
01 Nov
November 1, 2013

Today I was presented with puzzling issue that I had never encountered before. When accessing an item from a javascript object using underscore’s _.first() method I was getting two different items in Chrome and Firefox.

My object is an object with a string keys. The key is a numeric string (’01234′ ’12345′ etc) because javascript will trim off the leading zero if converted to a number.

Lets say in this example the order is correct. In Chrome this object when accessed will order 01234 after 23456 and firefox will order it before 12345. The only way to force an order of items is to convert the keys to numbers and it will be sorted by key numerically (dropping the leading 0 on 01234).

Interestingly enough I found that if the keys were alpha strings Firefox sorted them alphabetically and Chrome did not.

In this example chrome would respect the order of items in the object but Firefox would order them ‘a’, ‘b’, ‘c’.

This seriously calls into question why browsers are applying a sort to any object. The JSON spec does not dictate a default order there for browsers should not assume or try to assume any order other than the natural order of items.

Tags:
© Copyright 2017 Findaway. All rights reserved.