List Properties with Object.keys()
Write a JavaScript function that takes an object and returns an array of its property names (keys) using Object.keys(). The keys are returned in the same order as they appear in the object.
Object.keys() is a static JavaScript method that returns an array of a given object's own enumerable property names. It only includes properties directly on the object (not inherited through the prototype chain) and only enumerable properties. The order of keys follows ES2015 rules: integer-like keys in ascending order, followed by string keys in insertion order.
Object.keys() is part of a trio of reflection methods: Object.keys() returns property names, Object.values() returns property values, and Object.entries() returns both as [key, value] pairs. These methods are essential for iterating over objects, especially when combined with forEach() or for-of loops.
Time complexity is O(n) where n is the number of own enumerable properties. Space complexity is O(n) for the resulting array. The method does not modify the original object.
Edge cases include empty objects (returns empty array), objects with non-enumerable properties (not included), objects with symbol-keyed properties (not included in keys()), and null/undefined arguments (throws TypeError).
Example Input & Output
Single key
Non-integer keys preserve insertion order
Empty object
String keys
Two keys a and b
Algorithm Flow
Solution Approach
Return an array of all enumerable property names (keys) of an object using Object.keys(). This method extracts the keys of an object and returns them as an array. The order of keys follows the same order as a for-in loop.
Object.keys() only returns own enumerable properties, not inherited ones. For all keys including non-enumerable ones, use Object.getOwnPropertyNames().
Time complexity is O(n), space complexity is O(n).
Best Answers
function solution(obj) {
return Object.keys(obj);
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
