Course contentsShow
← JavaScript
Lesson 641 of 2,72315. ObjectsFree lesson

Object.keys() for Own Enumerable String Keys

Object.keys(obj) returns an array of the object's own enumerable string-keyed property names.

Object.keys() for Own Enumerable String Keys

You'll learn how to extract an array of an object's own property names using Object.keys().

What is Object.keys()?

Object.keys() is a built-in method that takes an object and returns a brand new array containing all of that object's own enumerable string-keyed property names. It's like asking an object, "Tell me all the keys you personally own (not inherited) that can be seen during enumeration."

This method automatically filters out:

  • Inherited properties from the prototype chain
  • Non-enumerable properties (like those with enumerable: false)
  • Symbol-keyed properties (only string keys are included)

Why Use Object.keys()?

While for...in loops also iterate over properties, Object.keys() gives you an actual array you can work with. This means you can use array methods like map(), filter(), forEach(), or check the .length property.

Think of it like getting a catalog: If an object is a filing cabinet, Object.keys() gives you a printed list of all the drawer labels you can access directly.

How It Works

const user = {
  name: 'Alice',
  age: 28,
  city: 'Boston'
};

const keys = Object.keys(user);
console.log(keys); // ['name', 'age', 'city']
console.log(keys.length); // 3

Notice the result is an array of strings, in the same order properties were defined.

Comparison with hasOwnProperty

Object.keys() does the filtering work for you—it's equivalent to looping with for...in and manually checking hasOwnProperty() for each property, but cleaner and more convenient.

Key Takeaway: Object.keys(obj) returns an array of an object's own enumerable string property names, making it easy to process keys with array methods.