Sub topic 8
Listing Properties and Their Order
This chapter assumes you can create objects, read and write properties with dot and bracket notation, and use delete. It also assumes you know that keys can be strings or symbols. You should be comfortable with arrays and for...of loops. Two topics come up briefly here and get their own chapters later: inherited properties from the prototype chain, and the enumerable attribute.
You list an object's properties whenever you serialize it, compare two objects, build a form from a config, or turn an object into an array to process. JavaScript has several listing tools. They differ in which keys they include and in the order they return them. Most bugs in this area come from picking a tool that includes more or fewer keys than you expected, or from assuming an order the language does not give you.
The working model: which keys, in which order
Each listing tool answers two questions:
- Which keys? Own or inherited, enumerable or not, strings or symbols.
- In what order? The language defines a fixed ordering rule, and every tool here follows it.
The ordering rule for an object's own keys is:
- Keys that are array indices come first, in ascending numeric order. An array index is a string such as
"0"or"42": a canonical non-negative integer up to 2³² − 2. - All other string keys come next, in the order they were created.
- Symbol keys come last, in the order they were created. Only some tools return them.
Here is the rule in action:
const o = { b: 1, 2: "two", a: 2, 1: "one" };
console.log(Object.keys(o)); // ["1", "2", "b", "a"]
for (const [k, v] of Object.entries(o)) {
console.log(k, v);
}
// 1 one
// 2 two
// b 1
// a 2The numeric keys 1 and 2 were written after b, but they still come first and in sorted order. b and a keep the order in which they were created. Alphabetical order plays no part. The keys also come back as strings ("1", not 1), because number keys are converted to strings when a property is created.
The listing tools compared
| Tool | Own | Inherited | Non-enumerable | Symbols | Returns |
|---|---|---|---|---|---|
| `for...in` | yes | yes (enumerable only) | no | no | loop over keys |
| `Object.keys(obj)` | yes | no | no | no | array of keys |
| `Object.values(obj)` | yes | no | no | no | array of values |
| `Object.entries(obj)` | yes | no | no | no | array of `[key, value]` |
| `Object.getOwnPropertyNames(obj)` | yes | no | yes | no | array of keys |
| `Object.getOwnPropertySymbols(obj)` | yes | no | yes | only symbols | array of symbols |
| `Reflect.ownKeys(obj)` | yes | no | yes | yes | array of all own keys |
This example sets up all four kinds of key and runs every tool on the same object:
const sym = Symbol("id");
const parent = { inherited: 1 };
const child = Object.create(parent);
child.own = 2;
child[sym] = 3;
Object.defineProperty(child, "hidden", { value: 4, enumerable: false });
const forIn = [];
for (const k in child) forIn.push(k);
console.log(forIn); // ["own", "inherited"]
console.log(Object.keys(child)); // ["own"]
console.log(Object.values(child)); // [2]
console.log(Object.getOwnPropertyNames(child)); // ["own", "hidden"]
console.log(Object.getOwnPropertySymbols(child)); // [Symbol(id)]
console.log(Reflect.ownKeys(child)); // ["own", "hidden", Symbol(id)]The symbol was added before hidden, but Reflect.ownKeys still lists it last because symbols always form the final group. for...in lists the object's own keys first and then walks up to parent. The prototype chapter explains how that walk works.
Using entries to transform objects
Objects have no map or filter method. The usual workaround is to convert the object to entries, change the array, and rebuild an object with Object.fromEntries:
const prices = { apple: 1.2, bread: 2.5, milk: 0.99 };
const withTax = Object.fromEntries(
Object.entries(prices).map(([name, price]) => [name, +(price * 1.2).toFixed(2)])
);
console.log(withTax); // { apple: 1.44, bread: 3, milk: 1.19 }
const cheap = Object.fromEntries(
Object.entries(prices).filter(([, price]) => price < 2)
);
console.log(cheap); // { apple: 1.2, milk: 0.99 }Object.fromEntries creates the keys in array order, so the rebuilt object keeps the original order. The same ordering rule still applies to it, which means numeric keys get re-sorted.
Edge cases in the ordering rule
What counts as an array index
Only strings in canonical integer form, from 0 to 4294967294, count as array indices. Strings that only look like numbers are ordinary string keys:
const o = {};
o.z = 1;
o["10"] = 1;
o["2"] = 1;
o["-1"] = 1;
o["1.5"] = 1;
o["01"] = 1;
o[4294967295] = 1;
o[4294967294] = 1;
console.log(Object.keys(o));
// ["2", "10", "4294967294", "z", "-1", "1.5", "01", "4294967295"]Negative numbers, decimals, keys with leading zeros, and anything at or above 2³² − 1 all keep creation order. The sort is numeric, so "10" comes after "2". A string sort would put it first.
Updating versus deleting and re-adding
When you assign a new value to an existing key, the key keeps its position. When you delete a key and add it again, it becomes a new key and moves to the end of its group:
const p = { a: 1, b: 2, c: 3 };
p.a = 100;
console.log(Object.keys(p)); // ["a", "b", "c"]
delete p.a;
p.a = 1;
console.log(Object.keys(p)); // ["b", "c", "a"]This matters when output order is visible to someone. JSON.stringify follows the same order as Object.keys, so a delete-then-re-add changes your serialized JSON. That can break snapshot tests and naive string comparisons.
Objects are the wrong tool for ordered numeric keys
If you key records by numeric ID and need insertion order, a plain object will sort the IDs for you. A Map keeps every key in insertion order, whatever its type:
const byId = { 30: "c", 10: "a", 20: "b" };
console.log(Object.values(byId)); // ["a", "b", "c"]
const m = new Map([[30, "c"], [10, "a"], [20, "b"]]);
console.log([...m.values()]); // ["c", "a", "b"]Common errors
Using `for...in` on arrays
for...in gives you string keys, not numbers, and it also includes any extra enumerable properties on the array. Use for...of, forEach, or array.entries() instead:
const arr = ["x", "y"];
arr.note = "extra";
for (const i in arr) console.log(typeof i, i);
// string 0
// string 1
// string note
for (const [i, v] of arr.entries()) console.log(typeof i, i, v);
// number 0 x
// number 1 yGetting inherited keys you didn't expect
If someone adds an enumerable property to a prototype, for...in will pick it up. To keep for...in, filter with Object.hasOwn. Usually it is simpler to switch to Object.keys:
const base = { shared: true };
const item = Object.create(base);
item.name = "lamp";
for (const k in item) {
if (Object.hasOwn(item, k)) console.log(k); // name
}Expecting symbols or hidden keys to show up
Object.keys, JSON.stringify, and spread-based copies skip non-enumerable keys. Object.keys and JSON.stringify also skip symbol keys. If metadata stored under a symbol "disappears", check which tool you used. Use Reflect.ownKeys when you truly need every own key.
Changing an object while you loop over it
With for...in, deleting a key that has not been visited yet means it will not be visited. Keys added during the loop may or may not be visited. Object.keys returns a snapshot array first, so changing the object inside a for...of loop over that array is safe and predictable:
const scores = { ann: 3, bob: 0, cid: 5 };
for (const key of Object.keys(scores)) {
if (scores[key] === 0) delete scores[key];
}
console.log(scores); // { ann: 3, cid: 5 }Choosing a tool
- You need values or pairs to process: use
Object.valuesorObject.entries. - You need key names only: use
Object.keys. - You need non-enumerable keys too, for example when debugging or copying exactly: use
Object.getOwnPropertyNames. - You need every own key, including symbols: use
Reflect.ownKeys. - You need inherited enumerable keys: use
for...in. - You need insertion order for numeric keys: use a
Mapinstead of an object.
Exercise
Predict the output of Object.keys(x) after this code runs: const x = { c: 1, "5": 1, b: 1 }; x["03"] = 1; x[1] = 1; x.c = 2; delete x.b; x.b = 3;
Show answer
["1", "5", "c", "03", "b"]. The array indices "1" and "5" come first in numeric order. The remaining string keys keep creation order. Assigning to c does not move it. "03" has a leading zero, so it is an ordinary string key. b was deleted and re-added, so it moves to the end.
Exercise
An object has an own enumerable key name, an own non-enumerable key secret, an own symbol key Symbol("tag"), and inherits an enumerable key kind. Which keys does each of these list: for...in, Object.keys, Object.getOwnPropertyNames, and Reflect.ownKeys?
Show answer
for...in lists name and kind. Object.keys lists name. Object.getOwnPropertyNames lists name and secret. Reflect.ownKeys lists name, secret, and Symbol(tag), with the symbol last.
Exercise
Write an expression that returns a new object containing only the properties of stock whose value is greater than 0. Use stock = { pens: 4, ink: 0, pads: 2 }.
Show answer
Object.fromEntries(Object.entries(stock).filter(([, qty]) => qty > 0)), which produces { pens: 4, pads: 2 } with the original key order kept.