Modern JavaScript: Property Order
Welcome to the Property Order lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
In many languages, properties in objects don't have a guaranteed order. (Some languages call their object-like data structures "hashes" or "dictionaries", but for our purposes here these are all the same thing.)
Consistent ordering is nice; it's one less thing to think about. Fortunately, modern versions of JavaScript guarantee object key ordering!
An object's keys will be in the order that they were defined in the object.
>
Object.keys({a: 1, b: 2});Result:
>
Object.keys({b: 2, a: 1});Result:
['b', 'a']
If we add more keys to the object after it exists, the ordering is preserved there too.
>
const user = {name: 'Amir', age: 36};user.email = 'amir@example.com';Object.keys(user);Result:
['name', 'age', 'email']
Object key order is even preserved when we deserialize JSON with
JSON.parse.>
const user = JSON.parse(`{"name": "Amir", "email": "amir@example.com", "age": 36}`);Object.keys(user);Result:
['name', 'email', 'age']
JSON.stringifypreserves that order as well, so round-tripping an object through JSON won't change the order of its keys.>
const user = JSON.parse(JSON.stringify({name: 'Amir', email: 'amir@example.com', age: 36}));Object.keys(user);Result:
['name', 'email', 'age']
There's one exception to the property order rule. It comes from an unusual part of JavaScript objects: they can have numbers as keys, and we can mix number keys with strings keys in the same object.
When an object has number keys:
- They always come first in the key list.
- They're always sorted numerically.
- They're always converted into strings (
1becomes'1').
Non-numeric string keys come after number keys, in the order that they were inserted into the object.
>
Object.keys({2: 'two', 1: 'one'});Result:
>
Object.keys({b: 'b', 1: 'one', a: 'a'});Result:
>
Object.keys({2: 'two', b: 'b', 1: 'one', a: 'a'});Result:
['1', '2', 'b', 'a']
This number-vs-string issue is an unfortunate complication. However, the good news is that objects with mixed number and string keys are uncommon, so this doesn't come up much. And when an object only has string keys, you can trust that they'll stay in insertion order.