Finding order in object properties
October 24, 2020
I remember being in school and having having it drilled into my head that if I wanted to have something with the ability to retain the order of its properties, I couldn’t use an Object. Instead I should use a more suitable data structure such as Maps, Lists, Stacks, or Arrays. To be honest those are probably still better options… But it’s not entirely the Wild West for Javascript Objects, there is some order!
Even though in the past the lack of order may have been true, browsers actually were treating objects the same way. When that was discovered, a standard was set and all modern browsers now follow it.
The order the property keys take is as follows:
Numbers (otherwise known as integer indices, think like what an Array may have), these are sorted numerically.
Note: it can even be a string like ‘1’, the term integer indices means it can be converted between string and number and retain the same value.
Normal String keys. These are your typical
foo
andbar
keys. They’ll appear in the order they’re added.Symbol‘s. These come last, in the order they’re added.
Anyways, that’s it, that’s all! If you’d like to learn more, you can read about it at Exploring JS where Dr. Axel goes into more detail and also sheds light on a number of Javascript’s other intricacies. I highly recommend it!
Inner ramblings of Jason Adam.
Follow me on Twitter