Skip to content

Commit f65af40

Browse files
author
Robin Ricard
authored
Merge pull request #25 from rricard/rb/enumeration-order
Clarified enumeration order of properties
2 parents 353cd0b + 06738ae commit f65af40

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

README.md

+31
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,37 @@ assert(Object.keys(@const { a: 1, b: 2 }) === @const ["a", "b"]);
218218
assert("a" in @const { a: 1, b: 2 });
219219
```
220220
221+
#### Note about ordering
222+
223+
When the properties of a const object are enumerated, its keys are enumerated in sorted order. This differs
224+
from regular objects, where insertion order is preserved when enumerating properties
225+
(except for properties that parse as numerics, where the behavior is undefined).
226+
227+
```js
228+
const obj = { z: 1, a: 1 };
229+
const constObj = @const { z: 1, a: 1 };
230+
231+
Object.keys(obj); // ["z", "a"]
232+
Object.keys(constObj); // ["a", "z"]
233+
```
234+
235+
The properties of const objects and const arrays are enumerated in this sorted order in order to
236+
preserve their equality when consuming them in pure functions.
237+
238+
```js
239+
const constObj1 = { a: 1, z: 1 };
240+
const constObj1 = { z: 1, a: 1 };
241+
242+
const func = (constObj) => {...} // some function with no observable side effects
243+
244+
assert(constObj1 === constObj2);
245+
assert(func(constObj1) === func(constObj2));
246+
```
247+
248+
If enumeration order for const objects and const arrays was instead insertion order, then:
249+
`const func = Object.keys;`
250+
would break the above assertion.
251+
221252
### Const array prototype
222253
223254
The const array prototype is a const object that contains the same methods as Array with a few changes:

0 commit comments

Comments
 (0)