What is Object.keys() used for?

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Easy
#JavaScript #Objects #JS Basics

Brief Answer

Object.keys() returns an array of names of all enumerable properties of an object. Convenient for iterating keys, checking property count, or converting object to other data structures.

const user = { name: 'John', age: 25 };
const keys = Object.keys(user);
console.log(keys); // ['name', 'age']

Full Answer

Object.keys() is a method to get all keys (property names) of an object. It’s very simple and often used when working with objects.

What Object.keys() Returns

Returns array of strings — names of all own enumerable properties:

const user = { name: 'John', age: 25 };
const keys = Object.keys(user);
console.log(keys); // ['name', 'age']

Simple Usage Examples

Counting Properties

const user = { name: 'John', age: 25, city: 'Moscow' };
const count = Object.keys(user).length;
console.log(count); // 3

Iterating Keys

const config = { theme: 'dark', lang: 'en' };
 
Object.keys(config).forEach(key => {
  console.log(key, config[key]); // theme dark, lang en
});

Important Features

1. Only Own Properties

const obj = { name: 'John' };
// Doesn't include inherited methods like toString
console.log(Object.keys(obj)); // ['name']

2. Only Enumerable Properties

const obj = { name: 'John' };
// Hide property
Object.defineProperty(obj, 'hidden', {
  value: 'secret',
  enumerable: false
});
 
console.log(Object.keys(obj)); // ['name'] - hidden not visible

When to Use Object.keys()

Instead of for…in for Keys

const user = { name: 'John', age: 25 };
 
// ❌ Complex way
for (let key in user) {
  if (user.hasOwnProperty(key)) {
    console.log(key);
  }
}
 
// ✅ Simple way
Object.keys(user).forEach(key => {
  console.log(key);
});

For Checking Property Existence

const obj = { a: 1, b: 2 };
 
// Check if object has properties
if (Object.keys(obj).length > 0) {
  console.log('Object is not empty');
}

Common Mistakes

1. Expecting Values

// ❌ Thinking we get values
const obj = { a: 1, b: 2 };
const result = Object.keys(obj);
console.log(result); // ['a', 'b'] - keys, not values!
 
// ✅ For values use Object.values()
const values = Object.values(obj);
console.log(values); // [1, 2]

2. Working with Non-objects

// ❌ Trying to use with primitives
Object.keys(42); // Error!
 
// ✅ Only with objects
Object.keys({ value: 42 }); // ['value']

Simple Rules

  1. Object.keys() — for getting object keys
  2. Array of strings — always returns array of property names
  3. Own — only own enumerable properties
  4. Order — preserved as in for…in
  5. Simplicity — simpler than for…in for getting keys

Object.keys() is convenient when you need to work only with object keys. This is simpler than for…in and doesn’t require inheritance checks.


Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪