Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Object.keys()

Object.keys returns an array of an object's own enumerable property names.

It is commonly used for iteration and validation.

Why We Need It

When working with objects, you often need to list keys for loops or checks.

Object.keys makes that simple and reliable.

Syntax

Object.keys(obj)

Basic Example

1. Basic keys

const user = { name: "Ava", role: "admin" };
const keys = Object.keys(user);

console.log(keys);

Returns ['name', 'role'].

Real World Example

2. Iterate

const settings = { theme: "dark", layout: "grid" };
Object.keys(settings).forEach((key) => {
  console.log(key, settings[key]);
});

Loop over keys to access values.

Multiple Use Cases

List Keys

Object.keys returns an array of an object's own enumerable keys.

It is useful for iteration and validation.

Pairs with values and entries

Use Object.values for values and Object.entries for key-value pairs.

Together they cover most inspection use cases.

Non-Objects

Object.keys works on arrays too, returning index strings.

It ignores properties in the prototype chain.

More Examples

3. Array keys

const items = ["a", "b"];
console.log(Object.keys(items)); // ['0','1']

Arrays are objects, so keys are indexes as strings.

4. Count properties

const user = { a: 1, b: 2, c: 3 };
const count = Object.keys(user).length;

console.log(count);

Count properties by keys length.

Comparison

Without

for (const key in obj) {
  if (Object.hasOwn(obj, key)) {
    console.log(key);
  }
}

With

Object.keys(obj).forEach((key) => console.log(key));

Common Mistakes and Fixes

Expecting inherited keys

Object.keys returns only own enumerable properties.

Using keys for values

Use Object.values when you only need values.

Assuming numeric order

Key order exists but should not be relied on for logic.

Interview Questions

What does Object.keys return?

An array of own enumerable keys.

Does it include inherited keys?

No, only own properties.

Why use Object.keys over for...in?

It avoids inherited properties without extra checks.

Practice Problem

Practice: Count how many properties an object has using Object.keys.

const user = { name: "Ava", role: "admin" };
// TODO: count keys

One Possible Solution

const user = { name: "Ava", role: "admin" };
const count = Object.keys(user).length;
console.log(count);

Frequently Asked Questions

What does Object.keys return?

An array of own enumerable property names.

Does it include inherited properties?

No, only own properties.

Can I use it on arrays?

Yes, it returns string indexes.

Try It Yourself

Try adding properties and see how the key list changes.