Skip to main content

Object.keys()

Object.keys() is a built-in JavaScript method that returns an array of all own (non-inherited) property names of an object as strings.


Syntax

javascript
Object.keys(obj)
  • obj - the object to get the list of keys from.
  • Returns an array of strings.

Example

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

All of the object's keys (own, enumerable) are returned in the array.


Features

  1. Returns only "own" properties (not ones inherited via prototype):
javascript
const person = { species: 'human' }; const user = Object.create(person); user.name = 'Tim'; console.log(Object.keys(user)); // ['name']
  1. Order of keys Matches the order they were added to the object (for regular properties).
  2. Works only with enumerable properties (if a property was created with enumerable: false, it will not appear in the list).

Example with an empty object

javascript
console.log(Object.keys({})); // []

Often used together with other methods

Get the list of values:

javascript
Object.values(user); // ['Tim', 25, 'Berlin']

Get an array of key-value pairs:

javascript
Object.entries(user); // [['name', 'Tim'], ['age', 25], ['city', 'Berlin']]

Iterate with forEach:

javascript
Object.keys(user).forEach(key => { console.log(`${key}: ${user[key]}`); });

Output:

javascript
name: Tim age: 25 city: Berlin

Summary

What it doesReturnsAccounts for the prototypeData type
List of an object's keysArray of stringsNoArray

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.