Object.keys() for Enumerable Properties
You'll learn how to extract an object's property names as an array using Object.keys().
When working with objects, you often need to know what properties an object has. Object.keys() is a built-in method that returns an array of an object's own enumerable property names (the keys).
What It Does
Think of an object as a filing cabinet with labeled drawers. Object.keys() gives you a list of all the drawer labels—not the contents, just the names.
const user = {
name: 'Alice',
age: 30,
city: 'Boston'
};
const keys = Object.keys(user);
console.log(keys); // ['name', 'age', 'city']
Important Details
Only enumerable properties: By default, properties you add to an object are enumerable. But if you used Object.defineProperty() with enumerable: false, those properties won't appear:
const obj = { visible: true };
Object.defineProperty(obj, 'hidden', {
value: 'secret',
enumerable: false
});
console.log(Object.keys(obj)); // ['visible'] — 'hidden' is skipped
Only own properties: Object.keys() doesn't include inherited properties from the prototype chain—only properties directly on the object itself.
Common Use Cases
You can loop through an object's keys to dynamically access values:
const scores = { math: 95, english: 88, science: 92 };
Object.keys(scores).forEach(subject => {
console.log(`${subject}: ${scores[subject]}`);
});
Key Takeaway: Object.keys() returns an array of an object's own enumerable property names, making it easy to iterate or inspect what keys an object contains.