Testing them out in a real simple case yields the same output:
const obj = {a: 5, b: 5};
console.log(Reflect.ownKeys(obj));
console.log(Object.keys(obj));
// Re
In addition to what the other answers have already mentioned, Reflect.ownKeys
is also guaranteed by the specification to return keys (and symbols) in the following order:
This order is required by the internal [[OwnPropertyKeys]] method which is invoked by Reflect.ownKeys.
In contrast, Object.keys
calls EnumerableOwnPropertyNames, which requires:
- Order the elements of
properties
so they are in the same relative order as would be produced by the Iterator that would be returned if the EnumerateObjectProperties internal method were invoked with O.
Where EnumerateObjectProperties explicitly does not specify any order in which the properties are returned:
The mechanics and order of enumerating the properties is not specified
So, if you want to be absolutely certain that, while iterating over object properties, you iterate in insertion order for non-numeric keys, make sure to use Reflect.ownKeys
(or Object.getOwnPropertyNames, which also invokes [[OwnPropertyKeys]]
).
(All that said, while Object.keys
, its variants, for..in
loops, and JSON.stringify
all officially iterate in an unspecified, implementation-dependant order, environments generally iterate in the same predictable order as Reflect.ownKeys
anyway, luckily)