Iteration Order and When It Matters
You'll learn: How JavaScript decides the order in which object properties appear during iteration—and why it's usually not something to worry about.
The Surprising Rule
When you iterate over object properties using methods like Object.keys(), Object.entries(), or for...in, JavaScript follows a specific order that might surprise you:
- Integer-like keys first (in numeric order)
- Then all other string keys (in insertion order)
- Then symbol keys (in insertion order)
"Integer-like" means strings that look like non-negative integers: "0", "1", "42", etc.
Example
const obj = {
name: "Alice",
3: "third",
age: 30,
1: "first",
city: "NYC"
};
console.log(Object.keys(obj));
// ["1", "3", "name", "age", "city"]
// Integer-like keys (1, 3) sorted numerically first,
// then string keys (name, age, city) in insertion order
Notice how "1" and "3" jump to the front and get sorted, even though we added them later.
When Does This Matter?
Rarely. In most real-world JavaScript, objects represent unordered collections of key-value pairs (like configuration settings or user data). The order shouldn't affect your logic.
However, it can matter when:
- You're serializing objects to JSON and care about display order
- You're building data structures where property order conveys meaning (though arrays are usually better for this)
- You're debugging and confused why keys appear in unexpected order
Key Takeaway: JavaScript iterates integer-like keys first (numerically sorted), then other keys in insertion order—but well-designed code rarely depends on object property order.