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
- 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']- Order of keys Matches the order they were added to the object (for regular properties).
- 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: BerlinSummary
| What it does | Returns | Accounts for the prototype | Data type |
|---|---|---|---|
| List of an object's keys | Array of strings | No | Array |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.