Object.keys()

ES5+

Returns an array of a given object's own enumerable property names.

Syntax

Object.keys(obj)

Parameters

obj Object

The object whose enumerable own property names are to be returned

Return Value

Array

An array of strings representing the object's enumerable properties

Examples

JavaScript
const obj = { a: 1, b: 2, c: 3 };
console.log(Object.keys(obj));
Output:
// ['a', 'b', 'c']

📌 When to Use

Use Object.keys() when you need to iterate over property names, count properties, check if an object has specific keys, or transform object keys into a different format. It is ideal for creating dynamic forms, validating object structures, or mapping object properties.

⚠️ Common Mistakes

Expecting inherited properties to be included - Object.keys() only returns own enumerable properties, not inherited ones from the prototype chain.

Assuming a specific order - while modern JavaScript engines maintain insertion order, relying on it for critical logic can be risky in edge cases.

Using Object.keys() on arrays - while it works, it returns string indices. Use array methods like forEach() or map() for arrays instead.

✅ Best Practices

Combine with map() or forEach() for transformations: Object.keys(obj).map(key => ({ key, value: obj[key] }))

Use Object.keys(obj).length to count properties instead of manually counting with a loop.

For checking if an object is empty, use Object.keys(obj).length === 0 as a reliable pattern.

⚡ Performance Notes

Object.keys() creates a new array on each call, which has O(n) time and space complexity where n is the number of enumerable properties. For large objects accessed frequently, consider caching the result if the object does not change. In hot paths, direct property access with known keys outperforms dynamic iteration.

🌍 Real World Example

Form Validation with Dynamic Fields

Use Object.keys() to dynamically validate all fields in a form object, checking for empty required fields.

const formData = {
  username: 'john_doe',
  email: '',
  password: 'secret123'
};

const requiredFields = ['username', 'email', 'password'];

function validateForm(data) {
  const emptyFields = Object.keys(data)
    .filter(key => requiredFields.includes(key) && !data[key]);

  if (emptyFields.length > 0) {
    return { valid: false, errors: emptyFields };
  }
  return { valid: true, errors: [] };
}

console.log(validateForm(formData));
// { valid: false, errors: ['email'] }

Related Methods