JavaScript Reflect.ownKeys and Property Enumeration
Quick answer
Different enumeration APIs select different sets of own string and symbol keys. Reflect.ownKeys returns all own keys, even non-enumerable ones.
How it works
Object.keys selects enumerable string keys; Object.getOwnPropertyNames selects all string keys; Object.getOwnPropertySymbols selects symbol keys. For ordinary objects, own key ordering places array-index string keys first in ascending order, then other string keys in creation order, then symbols in creation order. Exotic objects may differ. Reflect.ownKeys does not return inherited keys.
const s = Symbol("tag"); const o = {visible:1,[s]:2}; Object.defineProperty(o,"hidden",{value:3});console.log(Object.keys(o).length,Object.getOwnPropertyNames(o).length,Reflect.ownKeys(o).length);Expected output in Node.js:
1 2 3The three APIs include progressively different key categories.
const o = {b:1,10:2,2:3,a:4};console.log(Reflect.ownKeys(o).join(","));Expected output in Node.js:
2,10,b,aOrdinary index keys precede other strings in ascending numeric order.
Common mistakes
Do not treat Object.keys as a complete list of all property keys.
Practice
Create an object with a numeric key, a symbol and a hidden string key; compare four key lists.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Reflect.ownKeys and Property Enumeration — Knowledge Check
Apply the taught concept and predict the output.
Which API returns own symbol and non-enumerable string keys together?
What does getOwnPropertySymbols select?
Which keys come first for ordinary own-key ordering?
What is the exact console output in JavaScript Reflect.ownKeys and Property Enumeration example 1?
const s = Symbol("tag"); const o = {visible:1,[s]:2}; Object.defineProperty(o,"hidden",{value:3});console.log(Object.keys(o).length,Object.getOwnPropertyNames(o).length,Reflect.ownKeys(o).length);What is the exact console output in JavaScript Reflect.ownKeys and Property Enumeration example 2?
const o = {b:1,10:2,2:3,a:4};console.log(Reflect.ownKeys(o).join(","));