Monday, November 11, 2024

JavaScript Property order of object in for in loop

In JavaScript, the order of properties in an object literal when accessed via a for...in loop (or methods like Object.keys()) follows specific rules:

1. Integer Keys (in ascending order): 
Properties with integer names (like "0", "1", "42") are listed first, in ascending numerical order.

2. String Keys (in insertion order): 
After the integer keys, string properties (non-integer names) appear in the order they were added to the object.

3. Symbol Keys (in insertion order): 
Lastly, symbol properties appear in the order they were added to the object.

Example
Consider the following object:
const obj = {
  3: 'three',
  1: 'one',
  'name': 'Alice',
  2: 'two',
  [Symbol('id')]: 123,
  'lastName': 'Smith'
};

// Using for...in loop
for (const key in obj) {
  console.log(key, obj[key]);
}
Output
The output order would be:
  • 1 'one'
  • 2 'two'
  • 3 'three'
  • name 'Alice'
  • lastName 'Smith'
  • Symbol(id) 123

Explanation of the Order
  • Integer keys (1, 2, 3) appear first, in ascending numerical order, regardless of the order they were added.
  • String keys (name, lastName) follow, in the order they were added to the object.
  • Symbol keys appear last, in the order they were added.
Important Notes
  1. The for...in loop includes properties from the prototype chain, so it’s often paired with hasOwnProperty() to filter out inherited properties.
  2. This order applies to Object.keys() as well, but may differ slightly across environments before ES6 standardization.

No comments:

Post a Comment

Hot Topics