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));
// Result
['a', 'b']
['a', 'b']
When does Reflect.ownKeys(obj)
produce output different from Object.keys(obj)
?
First, an example (ES6Fiddle):
Here,
Reflect.ownKeys()
returns an array of the target object's own property keys. Namely, an array of all properties (enumerable or not) found directly upon the given object concatenated with an array of all symbol properties found directly upon the given object.Object.ownKeys()
will only return the enumerable properties.Enumerable properties are those that can be enumerated by a for...in loop, with the exception of properties inherited through the prototype chain. See the MDN description for more details.
Summary:
Reflect.ownKeys() is the equivalent of
Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))
which will return both enumerable and non-enumerable propertieswhereas
Object.keys() returns enumerable properties but does not return non-enumerable properties (which is a characteristic of Object.getOwnPropertyNames()).
Object.keys
returns only enumerable string keys;Reflect.ownKeys
returns both string and symbol keys regardless of their enumerability. Both operate on own properties only.Object.keys
returns an empty array if the argument is not an object and notnull
orundefined
(e.g.Object.keys(1)
), whereasReflect.ownKeys
throws aTypeError
.Reflect.ownKeys
was introduced with ES6 and is not supported in older JavaScript engines.Object.keys()
returns anarray
of strings, which are the object's own enumerable properties.Reflect.ownKeys(obj)
returns the equivalent of:The
Object.getOwnPropertyNames()
method returns an array of all properties (enumerable
or not) found directly upon a given object.The
Object.getOwnPropertySymbols()
method returns an array of allsymbol
properties found directly upon a given object.A small
fiddle
to demonstrate.